Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

compareTo() method always gives greater than

807598May 8 2006 — edited May 8 2006
I'm a college student trying to write a compareTo() method to compare two Rational Numbers, it's getting the numbers from another class, which I know works, because it's from the CD included w/ the textbook. I need to send in RationalNumbers r1 and r2 and have this method return greater, less or equal. Right now, I only get r1<r2 no matter what numbers I send in. The compareTo() is in the RationalNumber class, which is driven by a RationalTester class.
Any Ideas? I have no clue what I'm doing
<html>
<code>
//compareTo() Method, compares two rational numbers is in the RationalNumber class:
public double compareTo(RationalNumber r2)
{
double n1 = numerator;
double d1 = denominator;
double n2 = r2.getNumerator();
double d2 = r2.getDenominator();
double num1 = (n1/d1);
double num2 = (d1/d2);
double result = -2;
final double greater = 1;
final double equal = 0;
final double less = -1;

if (Math.abs(num1 - num2)< 0.0001)
{
result = equal;
}
if (num1 > num2)
{
result = greater;
}
if (num1 < num2)
{
result = less;
}
return result;
}
//this is in the RationalTester class:
if (r8>0)
{
System.out.println("r1 > r2");
}
if (r8==0)
{
System.out.println("r1 = r2");
}
if (r8<0)
{
System.out.println("r1 < r2");
}

</code>
</html>
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 5 2006
Added on May 8 2006
40 comments
573 views