This is for a Fraction program. I have private ints num and den, Fraction, and FractionInterface - the standard homework problem. I have done pretty much everything and now have been stuck for a few hours on the equals method. Since other is an Object, I can't equate it to Fraction. Here's what I have:
public boolean equals(Object other){
if (other == this){
return true;
} else {
return false;
}
}
This compiles but it gives incorrect results:
1/2 eq 1/2 = true
1/2 eq 1/2 = true
1/2 eq 1/2 = false
1/2 eq 1/2 = false
If I try other == Fraction, it doesn't compile. Thanks for any help!
You can test if other is an instance of FractionInterface and use a cast:
public boolean equals(Object other){
if (other == this){
return true;
} else if (other instanceof FractionInterface) {
FractionInterface fOther = (FractionInterface) other;
// compare numerator and denominator...
} else {
return false;
}
}
Note that instanceof will be false if other == null, so there's no need for a separate null check.
Try this out:
First, cast the other object
Fraction otherFraction = (Fraction) other;
Then, determine the condition that the two fractions are equivalent.
This will include some logic involving the comparing of numerator and denominators (expect to use getNum() and getDen() for the otherFraction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With