Re: Fractions equals each other problem

That won't work either because X/X1 is evaluated as an int and then you convert it to a double. The best method would be to use doubles everywhere in place of ints (based on my assumption of what you are trying to do).

A couple more observations. Your equals method is a method of the Fraction class. So a typical approach would be to pass in the num and denom as arguments and use the instance variables for the other num and denom.

And as you get more into Java, you should get into the habit of overriding hashCode if you override equals. Otherwise, the various hashMaps and such will not perform properly.

Re: Fractions equals each other problem

Originally Posted by jim829

Hmm, I could have sworn I had done this before and it didn't work. However, I stand humbly corrected!

It must've been bit rot; b.t.w. a Fraction implementation with an int numerator and denominator is next to useless; e.g. look at the arithmetic operations above: if any of those multiplications make an int overflow, the result will be incorrect. A solid Fraction class implementation is a nasty beast.

Re: Fractions equals each other problem

Originally Posted by jim829

That won't work either because X/X1 is evaluated as an int and then you convert it to a double. The best method would be to use doubles everywhere in place of ints (based on my assumption of what you are trying to do).

A couple more observations. Your equals method is a method of the Fraction class. So a typical approach would be to pass in the num and denom as arguments and use the instance variables for the other num and denom.

And as you get more into Java, you should get into the habit of overriding hashCode if you override equals. Otherwise, the various hashMaps and such will not perform properly.

Also, in this case the hashCode recommendation doesn't apply because this signature is different than the one inherited from the Object class.

Note: In an earlier post I discussed overriding equals. Just to clarify, you did *not* override equals because your equals signature takes an object of Fraction and not an object of Object. I hope this doesn't muddy the issue.

Re: Fractions equals each other problem

Re: Fractions equals each other problem

I gave it another look: if you properly normalize the numerator and denominator and stick the sign in (say) the numerator, the equals( ... ) method simply has to compare the two numerators and denominators for equality.