ITEC 120 Back to Assignment index page
   
Program 3 - The Comparable Interface
Submit your program files in a folder called RU07 in your directory on neelix.

Modify this Rational.java class file to implement the comparable interface.

To implement the Comparable interface, you must write a compareTo method for your object. As defined in the java.lang.Comparable documentation:

public int compareTo(Object o)
Compares this object with the specified object (o) for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object (o).

To perform the comparison, you will need to divide the numerator and denomonator of each rational object to get a floating point value. Use a tolerance of .0001 to compare the two floating point values. (So, if the two numbers are within .0001 of each other, you can say they are equal.)

Notice that the formal parameter for compareTo is an Object (and not a Rational). All objects are derived from the Object class, so you may pass any object to this method and its type will match Object. However, inside your method compareTo, you will want to access the instance data of o (lowercase letter o). o does not have instance data numerator, so you must cast o to be a Rational object, thus:

((Rational)o).numerator

The red parenthesis are necessary because you want to only cast o to be a Rational object. If you leave them out, you will be attempting to case o.numerator to be a Rational object, which you don't want. (numerator is an int).

Write a driver program to test the compareTo method that you wrote. The driver should ask the user for the numerator and denominator of two rational numbers, then compare them and tell the user which is bigger. the driver should then ask the user if he/she would like to enter another number.



Sample run:
Program Outputs Enter numerator for the first rational number:
User Inputs 5
Program Outputs Enter denominator for the first rational number:
User Inputs 6
Program Outputs

Enter numerator for the second rational number:

User Inputs 7
Program Outputs

Enter denominator for the second rational number:

User Inputs 8
Program Outputs

5/6 is less than 7/8.

Would you like to enter 2 more numbers? (y/n)

User Inputs y
Program Outputs Enter numerator for the first rational number:
User Inputs 1
Program Outputs Enter denominator for the first rational number:
User Inputs 2
Program Outputs

Enter numerator for the second rational number:

User Inputs 4999999
Program Outputs

Enter denominator for the second rational number:

User Inputs 10000000
Program Outputs

1/2 is the same as 4999999/10000000.

Would you like to enter 2 more numbers? (y/n)

User Inputs

n


TURNING IN YOUR PROGRAM: You will turn in two files. You'll have the driver program and the Rational class which you have modified. Submit both files to neelix in a folder called RU07 in your folder.