I am trying to implement a Comparable interface in a Fraction class that I coded for an exercise problem in CodeHS. The objective of the code is to compare two fractions and determine whether they are the same or not. However, when I check my code, it says that I haven't implemented '.equals' which I am supposed to implement. I added a equals method in my code but I don't know where I can put in '.equals' anywhere else.
Here's my assignment description:
In this exercise we are going to extend the Fraction class to have it implement the Comparable interface. To do this you need to implement the compareTo method:
public int compareTo(Fraction other) It is not required to implement the equals method to implement the Comparable interface, but we will implement that one here as well:
public boolean equals(Object other) equals should return true only if the Object other is an instanceof the Fraction class, AND the result of calling compareTo on other is 0.
My code:
public class Fraction implements Comparable<Fraction>
{
private int num;
private int den;
public Fraction(int numerator, int denominator)
{
num = numerator;
den = denominator;
}
public int compareTo(Fraction other)
{
int num2 = other.getNumerator(); // 1
int den2 = other.getDenominator(); // 4
int diff;
System.out.println(den - den2);
if ((den % den2 == 0) && (den - den2 != 0))
{
num2 *= (den / den2);
diff = num - num2;
return diff;
}
else if ((den2 % den == 0) && (den - den2 != 0))
{
num *= (den2 / den);
diff = num - num2;
return diff;
}
else if ((den % den2 == 0) && (den - den2 == 0))
{
diff = 0;
return diff;
}
else
{
diff = (num * den2) - (num2 * den);
System.out.println(diff);
return diff;
}
}
public boolean equals(Object other)
{
return other instanceof Fraction && compareTo((Fraction)other) == 0;
}
public int getNumerator() {
return num;
}
public int getDenominator() {
return den;
}
public void setNumerator(int x) {
num = x;
}
public void setDenominator(int x) {
den = x;
}
public String toString() {
return num + "/" + den;
}
}
The assignment description My test cases
I tried to replace the equal operator but my code wouldn't compile. My code is running fine and the comparing function is working; it's just that in order to fulfill all the assignment's requirements, I have to implement '.equals'. I assumed implementing '.equals' was adding the equals method so I don't really know where to go from here.