Computer Science 15-100 (APEA Section E), Summer 2008
Homework 7b
Due:  Tue 5-Aug-2008 at 9:00am (online submission and physical copy)
(no late submissions accepted).



  1. Better Fraction class
    Starting with the Fraction class we developed in class, add methods for "subtract", "multiply", and "divide", along with appropriate test methods.  Also, add "toInt" and "toDouble", which return the value of the fraction to the nearest int or double value (and include test methods for these, too!).  Also, you must deal with negative numbers and zero as such:

    1. A negative numerator and denominator must be reduced to both being positive.

    2. Any negative number must have a negative numerator and positive denominator.

    3. Zero must be represented as a zero in the numerator and a 1 in the denominator.

    4. Dividing by zero (in any way it might occur) must throw an ArithmeticException (see the online API for details).
       

  2. Better Polynomial Class
    Starting with the Polynomial class we developed in class, change the class so that it represents the coefficients using Fraction values (from the previous problem) rather than int's.  Also, add a method, "multiply", which takes a second polynomial ("that") and returns a third polynomial that is the result of multiplying "this" times "that".  Note that you'll need to gather like terms when you multiply, since polynomials include only one coefficient for each power.  For example, (n+2) times (3n+4) equals (3n^2 + 4n + 6n + 8), but you must gather the like terms to get (3n^2 + 10n + 8).  Finally, add a reasonable "toString" method (do not display powers where the coefficient is zero, and do not display coefficients that equal 1) and suitable test methods.
     

  3. Sortable ArrayListOfFractions
    Create a class called ArrayListOfFractions.  It will be a custom implementation of a class similar to java.util.ArrayList, but it will not use any classes from java.util.* except for java.util.AbstractList, which in fact you will extend, overriding these methods:
       get(int index),
       set(int index, Object element)
       add(int index, Object element)
       add(Object element)
       remove(int index)

    You must store the values in an instance variable that is an array of Fractions (something like:  private Fraction[] values), and this array must double in size as needed when there is no room to add a new element.  Your set and add methods should only work for Fraction objects, and should throw a suitable RuntimeException for other object types (this is easily achieved by casting the Object to a Fraction -- this will work for Fractions and will throw an exception otherwise).  In order to make an ArrayListOfFractions sortable using Collections.sort, you will have to make your Fractions class implement the Comparable interface.  Include suitable test methods for all of this.


Carpe diem!