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
But the actual output returns all zero. please tell me how to fix it.
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.