I'm creating a program that adds fractions together. That being said however, my program does not seem to be responding correctly. Everytime I run the client code, it outputs
18, when I want it to add 2/6 and 1/6.
// Constructor //
public class RationalNumber
{
int num;
int den;
private int gcd(int x, int y)
{
while(y != 0)
{
int temp = x % y;
x = y;
y = temp;
}
return x;
}
public RationalNumber(int numerator, int denominator)
{
if(denominator == 0)
{
throw new IllegalArgumentException("You can't divide by zero.");
}
else
{
num = numerator;
den = denominator;
}
}
public RationalNumber()
{
this (0,1);
}
public boolean equals(Object o)
{
if (o instanceof RationalNumber)
{
RationalNumber other = (RationalNumber) o;
int r1 = this.gcd(num,den);
int r2 = this.gcd(other.getNumerator(),other.getDenominator());
return num/r1 == other.num/r2 && den/r1 == other.den/r2;
}
else
{
return false;
}
}
public int getDenominator()
{
return den;
}
public int getNumerator()
{
return num;
}
public void reduce()
{
int d;
while (true)
{
d = this.gcd(this.num,this.den);
if (d == 1)
{
return;
}
this.num /= d;
this.den /= d;
}
}
public int add(RationalNumber r1)
{
int commonDen = den * r1.getDenominator();
int num1 = num * r1.getDenominator();
int num2 = r1.getNumerator() * den;
int sum = num1 + num2;
return sum;
}
public String toString()
{
if (den == 1)
{
return num + "";
}
else
{
return num + "/" + den;
}
}
}
// Client Code //
public class RationalNumberTest
{
public static void main (String[] args)
{
RationalNumber r1 = new RationalNumber(2,6);
RationalNumber r2 = new RationalNumber(1,6);
System.out.println(r1.add(r2));
}
}