logo Practice-It logo


Related Links:
Author: Roy McElmurry

Suppose you have a pre-existing class Rational that represents fractions such as 1/2 or 5/8. The class has the following data and behavior:

Field/Constructor/Method Description
private int numerator value on the top of the fraction (numerator)
private int denominator value on the bottom of the fraction (denominator)
public Rational(int n, int d) makes a rational number to store n/d
public int getNumerator() returns the fraction's top value (numerator)
public int getDenominator() returns the fraction's bottom value (denominator)
public double numericValue() returns the fraction's actual real number value, such as 0.5 for 1/2 or 0.375 for 3/8
public void normalize() reduces numerator/denominator by greatest common factor; for example, converts 3/6 to 1/2
public String toString() returns String such as "5/8"

Your task is to modify the class to be Comparable by adding an appropriate compareTo method. Rational numbers are compared by value. For example, 1/2 is a larger value than 3/8 so it is considered to be "greater" than it; and 4/17 is a smaller value than 2/3, so it is considered to be "less than" 2/3. If two fractions have the same numeric value, such as 1/2 and 4/8, break ties by considering the one with the smaller numerator and denominator to be "less." So in the previous example, 1/2 would be "less than" 4/8. If two rational numbers have exactly the same numerator and denominator, they are considered to be "equal." Your method should not modify either of the rational numbers' state. You may assume the parameter passed is not null.

public class Rational Comparable<Rational>{ 
    // write any added code here 
Type your solution here:

This is a partial class problem. Submit code that will become part of an existing Java class as described. You do not need to write the complete class, just the portion described in the problem.

You must log in before you can solve this problem.

Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.