Problem 7.2

CIS 210 Home Page Last updated 2007/11/06 11:20:13

In this assignment you will implement the Java interface Comparable for comparing objects. When a class implements an interface, it must provide definitions of the methods specified by the interface. This is essentially a contract: by implementing the interface specification, the class is guaranteed to have the behavior of the interface. In the case of the Comparable interface, the idea is to have a standard way for objects to compare themselves to other objects (of the same type). With such an interface, it is possible to implement searching and sorting algorithms on lists of Comparable objects without knowing anything about the objects except that they are Comparable.

We will start with the RationalNumber class provided in RationalNumber.java. This is loosely based on the implementation in section 11.5 in Liang - read the text for more details about rational numbers and the implementation. Objects of this class type behave like rational numbers, which are fractions, i.e., the quotient of two integers. The class provides methods to perform arithmetic. The fractions are reduced to lowest terms and if the fraction is negative, the numerator has the sign. The driver code in TestRational.java lets you input two rational numbers and does some arithmetic.

Your job is to revise RationalNumber to implement the Comparable interface. This will allow two RationalNumber objects to be compared. To make this more interesting, your implementation must incorporate a notion of tolerance. That is, since we are dealing with fractions the could correspond to very small values, your implementation must consider two rational numbers to be equal if they are very close to each other. For this assignment, we will define "very close" to be within 0.0001 of each other.

In addition to implementing the Comparable interface, you must provide the method equals.

Start by compiling the RationalNumber code and the driver code so that you can see that the class works to do arithmetic. After you implement the Comparable interface and the equals method, uncomment the last lines of the driver code and try some tests to make sure that your implementation works, and that two rational numbers compare as equivalent if they are within 0.0001 of each other.

You should expect to see the following output for fractions 1/10000 and 2/10000:


(1/10000).equals(1/5000) is true
(1/10000).compareTo(1/5000) is 0
and the following for fractions 1/10000 and 2/1000:

(1/10000).equals(1/500) is false
(1/10000).compareTo(1/500) is -1

What to turn in

Turn-in: RationalNumber.java, the source code for your RationalNumber class implementing the Comparable interface and the equals method.

Notes and Hints