How to output basic arithmetic operations correctly?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • monkey0525
    New Member
    • Apr 2010
    • 11

    #1

    How to output basic arithmetic operations correctly?

    I'm creating a program that adds and subtracts fractions together. That being said however, my program does not seem to be responding correctly. Every time I run the client code, it outputs
    4/4, when I want it to add 1/2 and 1/2 (instead of 1), and 6/36, when I subtract 2/6 and 1/6 (instead of 1/6). My constructor code and client code is as follows:

    Code:
     // 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 void reduce()
    	{
    		int d;
    		while (true)
    		{
    			d = this.gcd(this.num,this.den);
    			if (d == 1)
    			{
    				return;
    			}
    			this.num /= d;
    			this.den /= d;
    		}
    	}			
    	public RationalNumber add(RationalNumber r1)
    	{
    		int commonDen = den * r1.getDenominator();
    		int num1 = num * r1.getDenominator();
    		int num2 = r1.getNumerator() * den;
    		int sum = num1 + num2;
    		
    		return new RationalNumber (sum, commonDen);
    	}
    	public RationalNumber sub(RationalNumber r1)
    	{
    		int commonDen = den * r1.getDenominator();
    		int num1 = num * r1.getDenominator();
    		int num2 = r1.getNumerator() * den;
    		int dif = num1 - num2;
    		
    		return new RationalNumber (dif, commonDen);
    	}
    }
    Code:
     // Client Code //
    public class RationalTest
    {
       public static void main (String[] args)
       {
    		RationalNumber r1 = new RationalNumber(2,6);
    		RationalNumber r2 = new RationalNumber(1,6);
    		RationalNumber r3 = new RationalNumber(1,2);
    		RationalNumber r4 = new RationalNumber(1,2);
    		
    		System.out.println(r1.add(r2));
    		
    		System.out.println(r3.sub(r4));
    	}
    }
    Hopefully this code segment is sufficient enough in exchange for your help. Thank you for your time.
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    the methods getDenominator( ) and getNumerator() appear to be missing from class RationalNumber

    Comment

    • monkey0525
      New Member
      • Apr 2010
      • 11

      #3
      Ah, no. It does exist. I just excluded it from my code to make it as small as possible. I apologize that it exceeds 20 lines.

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        You never call your reduce function.

        Comment

        Working...