0

Hello, well I'm doing a rational class and i'm having trouble with the subtraction part. I have done add, multiply, and division correctly. Therefore, I would like a little help on subtraction, and i'm set.

```
public class Rational {
// TODO Auto-generated method stub
//Data members
private int numerator;
private int denominator;
//Constructors
Rational()
{
numerator = 0;
denominator = 1;
}
Rational(int num, int den)
{
numerator = num;
denominator = den;
}
//Accessors
public int getNumerator()
{
return numerator;
}
public int getDenominator()
{
return denominator;
}
// Modifiers
public void setNumerator(int num)
{
numerator = num;
}
public void setDenominator(int den)
{
denominator = den;
}
public Rational inputRational(){
Scanner input = new Scanner(System.in);
System.out.println("Enter numerator");
numerator = input.nextInt();
System.out.println("Enter Denominator");
denominator = input.nextInt();
return new Rational(numerator, denominator);
}
public String toString()
{
return numerator + "/" + denominator;
}
private int gcd(int m, int n)
{
int r;
while(n != 0)
{
r = m % n;
m = n;
n = r;
}
return m;
}
//Adding
public Rational add(Rational f)
{
int num;
int den;
num = (numerator * f.denominator) + (f.numerator * denominator);
den = denominator * f.denominator;
return new Rational(num, den);
}
public void sub(Rational f1)
{
numerator = (numerator * f1.numerator) - (f1.numerator * denominator);
denominator = denominator * f1.denominator;
}
public Rational mul(Rational f)
{
int num;
int den;
num = numerator * f.numerator;
den = denominator * f.denominator;
return new Rational(num, den);
}
public void div(Rational f1, Rational f2)
{
this.numerator = f1.numerator * f2.denominator;
this.denominator = f1.denominator * f2.numerator;
}
public static double divided(Rational f1, Rational f2)
{
double value;
value = (f1.numerator/f2.denominator)*(f2.denominator/f2.numerator);
return value;
}
}
```

Here is my test rational class.

```
public class testRational {
public static void main(String[] args) {
// TODO Auto-generated method stub
Rational f1 = new Rational();
Rational f2 = new Rational();
Rational f3 = new Rational();
f1.inputRational();
f2.inputRational();
f3 = f1.add(f2);
System.out.println(f1.toString() + " + " + f2.toString() + " = " + f3.toString());
f3.sub(f1);
System.out.println(f1.toString() + " - " + f2.toString() + " = " + f3.toString());
f3 = f1.mul(f2);
System.out.println(f1.toString() + " * " + f2.toString() + " = " + f3.toString());
f3.div(f1, f2);
System.out.println(f1.toString() + " / " + f2.toString() + " = " + f3.toString());
System.out.println(Rational.divided(f1,f2));
f1.setNumerator(2);
f2.setDenominator(5);
System.out.println("Numerator: " +f1.getNumerator());
System.out.println("Denominator: "+f2.getDenominator());
}
}
```

So let's say I input 3/4 and 1/2. it prints out 3/4 - 1/2 = 6/32, which is wrong. Everything else, is correct. So anyhelp is appreciated.