Hello all, I have to create a Fraction class and a test class for an assignment and I have run into a problem getting my reduce() method to work. Could you please take a look, any feedback would be much appreciated.
Here is the Fraction class:
package fraction;
public class Fraction
{
private int num;
private int den;
public Fraction(int a, int b)
{
num = a;
den = b;
}
public Fraction()
{
num = 1;
den = 1;
}
public String toString()
{
return num + "/" + den;
}
public double getDecimal()
{
double decimal = ((double)num / den);
return decimal;
}
public void reduce()
{
int n = num;
int d = den;
while(n != d)
{
if(n > d)
n = n - d;
if(d > n)
d = d - n;
}
}
public String toMixed()
{
int a = num;
int b = den;
int whole = num / den;
while(a != b)
{
if(a > b)
a = a - b;
if(b > a)
b = b - a;
}
Fraction g = new Fraction(num % den / b, den / b);
if(whole > 0)
return whole + " " + g.toString();
else
return g.toString();
}
}
And here is the FractionTest class:
package fraction;
import java.util.Scanner;
public class FractionClassTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int choice = 0;
Fraction[] fraction;
fraction = new Fraction[5];
fraction[0] = new Fraction(8, 24);
fraction[1] = new Fraction(30, 75);
fraction[2] = new Fraction(27, 48);
fraction[3] = new Fraction(75, 45);
fraction[4] = new Fraction(5, 4);
System.out.println("Enter 1 to test the toString() method, 2 to test the reduce() method,"
+ " 3 to test the toMixed method, or 4 to quit: ");
choice = input.nextInt();
while(choice != 4)
{
if(choice == 1)
for(int i = 0; i < fraction.length; i++)
{
System.out.println(fraction[i].toString());
}
if(choice == 2)
for(int i = 0; i < fraction.length; i++)
{
fraction[i].reduce();
}
if(choice == 3)
for(int i = 0; i < fraction.length; i++)
{
System.out.println(fraction[i].toMixed());
}
System.out.println("Enter 1 to test the toString() method, 2 to test the reduce() method,"
+ " 3 to test the toMixed() method, or 4 to quit: ");
choice = input.nextInt();
}
}
}