void sort(List<T>)
method.
This method will sort a list of Comparable objects.
(This is similar in some ways to Lab 1 - but is intended to provide a bit of practice with inheritance and polymorphism in Java.) Pay particular attention to parameter types, return types, placing code in the "best" place ...
Let's consider 3 types of RationalNumber's: ProperFraction's, ImproperFraction's and WholeNumber's. (Here you have 4 Java class names.)
Design and code Java classes as described below. ProperFraction, ImproperFraction and WholeNumber are all derived from RationalNumber. RationalNumber will have 2 private - yes private - (non-negative) int members, representing the numerator and denominator. Since this class is immutable as defined here, they can also be declared final. The derived classes will have no "new" data members.
Design and code a class SortFractions that will read and output a List of fractions as shown below. The List will also be output in "reduced" form (and in Exercise 3 in ascending order by value).
SortFractions will have a getRational method to parse an input string as shown by the following code fragment
String s; RationalNumber r; List<RationalNumber> myList = new ArrayList<>(); System.out.println("Read strings until ctrl/d ..."); System.out.print("Input value? "); while (in.hasNextLine()) { s = in.nextLine(); r = getRational(s); myList.add(r); System.out.print("Input value? "); }
Use the sort method from the Collectons class to sort the list of
RationalNumbers into ascending order.
This method sorts Comparable objects. Comparable objects implement a
public int compareTo(T o)
method that imposes a "natural Ordering" on them.
compareTo "returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object."
In addition, the Comparable class must inform the Java compiler that it does
implement this function by stating that it implements the Comparable interface.
For example ...
public class RationalNumber implements Comparable<RationalNumber> {
Here is some expected behaviour ...
...$ java SortFractions Let's Sort a list of fractions. (as many as you want) (Use ctrl/d to indicate the end of the list.) Input value? 3/4 Input value? 2/4 Input value? 4/4 Input value? 5/4 Input value? 6/4 Input value? 8/4 Input value? 0 Input value? 0/5 Input value? 5 Input value? 9/15 Input value? 1/99 Input value? Before sorting ... 3/4 2/4 4/4 5/4 6/4 8/4 0 0/5 5 9/15 1/99 In lowest terms ... 3/4 1/2 1 5/4 3/2 2 0 0/1 5 3/5 1/99 After sorting ... 0 0/5 1/99 2/4 9/15 3/4 4/4 5/4 6/4 8/4 5 ...$
This assignment is due at the beginning of the Tuesday lab class next week (3:30 p.m.) - and the submit program will enforce this!