0

after c++ i am trying to learn some java, and i have a question about the code i have been working on. I am working on a Fraction class and i got stuck in reduce section. Since the method did not let me to return both "num" and "den", I had to return "n" This is my method

public double reduce() {
    int n = num;
    int d = den;

    while (d != 0) {
        int t = d;
        d = n % d;
        n = t;
    }
    int gcd = n;

    num /= gcd; //num = num / greatestCommonDivisor
    den /= gcd; //den = den / greatestCommonDivisor
    return n;
}

I am trying to do "return num, den;" however it does not let me.

and this is what i get

to reduced test for  100/2 is 2.0
to reduced test for  6/2 is 2.0

when i run

System.out.println("to reduced test for  " + f4.toString() + " is " + f4.reduce());
System.out.println("to reduced test for  " + f6.toString() + " is " +f6.reduce());

Why do i get the 2 when when i am supposed to get 50/1 and 3/1 ? If the IDE let me return num and den at the same time, would that have fixed it?

Thanks

UniQuadrion
  • 149
  • 1
  • 2
  • 13
  • 1
    This is a n-times duplicate, here: http://stackoverflow.com/questions/8557716/how-to-return-multiple-values-in-java or here: http://stackoverflow.com/questions/16609269/best-practice-for-returning-multiple-values-in-java – Raul Guiu Feb 05 '14 at 23:55

2 Answers2

3

Java has no native way of doing this, you only can return one Object or primitive. This leaves you two options:

  • Return an array with length 2.

    public int[] reduce()
    {
        ...
        return new int[]{num, den};
    }
    
  • Return an object of a wrapper class containing the two numbers.

    public Fraction reduce()
    {
        ...
        return new Fraction(num, den);
    }
    
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
0

It looks like your reduce method is modifying the object. It's unclear what exactly you want to return. If you want the fraction to return itself, then return this;, with the method returning a Fraction in the declaration.

rgettman
  • 176,041
  • 30
  • 275
  • 357