I am trying to write a class Rational that had a few methods relating to adding, subtracting, etc. I want to make it so that within the constructor, I add the values to the private variables and find the GCD to find simplify the fraction. The problem I run into is with my if statements. I want to check if the numbers within the object parameter are negative so I use the if statement to check. The only problem is when I run the program, it doesn’t give me a negative value i.e. I have Rational p = new Rational(-24, 48) and it only returns 1/2.
public class TestRational {
public static void main(String... args) {
Rational p = new Rational(-24, 48);
}
public Rational(long a, long b){
numerator = a;
denominator = b;
boolean isNegative = false;
if (numerator*denominator < 0)
isNegative = true;
long gd = gcd(numerator, denominator);
numerator /= gd;
denominator /= gd;
if (isNegative)
numerator = -numerator;;
}
private long gcd(long p, long q){
//checks to see if numerator greater than denominator
if(p<q)
return gcd(q,p);
if(Math.abs(q) == 0)
return p;
long remainder = Math.abs(p)%Math.abs(q);
return gcd(Math.abs(q), Math.abs(remainder));
}
}
You dont need this
So the constructor becomes
Hope it works …