Search code examples
javacompareto

How to fix the code in method compareTo to make it not only return all value in zero?


My assignment is to write the code within the compareTo block to compare three objects from the main method. I can compile the code but when it runs, I got all return value in Zero.

Each parameter in the object is numerator and denominator.I divide these numbers in each object,compare an object to one another and return them into type int.

public class Ratio implements Comparable {
    protected int numerator;
    protected int denominator;
    public Ratio(int top, int bottom) //precaution: bottom !=0
    {
        numerator = top;
        denominator = bottom;
    }
    public int getNumerator() {
        return numerator;
    }
    public int getDenominator() {
        return denominator;
    }


    public int compareTo(Object other) { //precaution: other is non-null Ratio object
        //my own code
        int a = this.getNumerator() / this.getDenominator();
        int b = ((Ratio) other).getNumerator() / ((Ratio) other).getDenominator();
        int difference = a - b;

        if (difference == 0) {
            return 0;
        } else if (difference > 0) {
            return 1;
        } else {
            return -1;
        }
    }
}

These are objects given in main method.

Ratio r1 = new Ratio(10,5);
Ratio r2 = new Ratio(7,3);
Ratio r3 = new Ratio(20,10);

I expect the output to be

  • r1 compare to r2 =-1
  • r1 compare to r3 =0
  • r2 compare to r1 =1
  • r2 compare to r3 =1
  • r3 compare to r1 =0
  • r3 compare to r2 =-1
  • r3 compareto r3 =0

But the actual output returns all zero. please tell me how to fix it.


Solution

  • When you divide by / you get the result without the remainder. That's why every Ratio in your example equals to 2 and the differences are all zeros.

    You need to take into account the modulus operator (%), which gives you the remainder you need for the accurate difference between your Ratio instances.