reducing a fraction


public class fraction
{
	private int x, y, GCD, num, denom, newNum, newDenom;
	public static final double base = 10;
	
	public fraction()
	{
		num = 0;
		denom = 1;
	}
	public fraction(int initialNum, int initialDenom)
	{
		if (initialNum == 0)
		{
			System.out.println("The fraction equals zero");
		}
		else if (initialDenom == 0)
		{
			System.out.println("The fraction cannot exist");
		}
		else 
		{
			num = initialNum;
			denom = initialDenom;
		}
	}
	private fraction simplify()
	{
		int GCD = getGCD();
		num /= GCD;
		denom /= GCD;
		fracton f = new fraction(newNum, newDenom);
		return f;
	}
	private static int getGCD(int x, int y)
	{
		x = num;
		y = denom;
		while (num != denom)
		{
			if (x > y)
				x -= y;
			else 
				y -= x;
		}
		return x;
	}
	
	public void setNum(int newNum)
	{
		num = newNum;
	}
	public void setDenom(int newDenom)
	{
		denom = newDenom;
	}
	public double getValue()
	{
		return ((double) num)/ ((double) denom);		
	}
	public int getnum()
	{
		return num;
	}
	public int getdenom()
	{
		return denom;
	}	
	public String toString()
	{
		String temp = num + "/" + denom;
		return temp;
	}
}



import java.util.Scanner;

public class testFraction
{
	public static void main(String[] args)
	{
		fraction f1 = new fraction();
		Scanner keyboard = new Scanner(System.in);
		
		System.out.println("enter the value of the numerator.");
		int num = keyboard.nextInt();
		f1.setNum(num);
		
		System.out.println("enter the value of the denominator.");
		int denom = keyboard.nextInt();
		f1.setDenom(denom);
		
		System.out.println(f1.toString());
		System.out.println("as a rational number: " + getValue());
		
		
	}
}


sigh… i don’t understand how to mix non static and static variables in this program.
so far, the problem i seem to have is making a method for the Great Common Denominator. Why?


while (num != denom)
		{
			if (x > y)
				x -= y;
			else 
				y -= x;
		}
		return x;


Well, this part doesn’t look right, since the loop doesn’t change the values of num or denom.

And, I’ve never actually programmed in Java, but do you need to pass arguments for “int GCD = getGCD()”?

(By the way, GCD stands for "Greatest Common Divisor.)

I concur that getGCD() looks seriously flawed. I think it should be something like this:



  private int getGCD()
  {
	x = num;
	y = denom;
	while (x != y)
	{
	    if (x > y)
		x -= y;
	    else 
		y -= x;
	}
	return x;
  }


A much more efficient way to compute the GCD(x,y) is to use the Euclidean algorithm. It won’t make much of a difference if x and y are close in size, but if one is a lot bigger than the other, the loop in the algorithm given above will execute many more times.


int gcd(int x, int y){
  int q, r=1;
  int temp;
  int last;

  if (x > y) {
    temp = y;
    y=x;
    x=temp;
  }

  while (r > 0) {
    last = x;
    q = y / x;
    r = y % x;
    y = x;
    x = r;
  }
  return last;  
}