Java how to return two variables? -


this question has answer here:

after c++ trying learn java, , have question code have been working on. working on fraction class , got stuck in reduce section. since method did not let me return both "num" , "den", had return "n" 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 trying "return num, den;" not let me.

and

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

when run

system.out.println("to reduced test  " + f4.tostring() + " " + f4.reduce()); system.out.println("to reduced test  " + f6.tostring() + " " +f6.reduce()); 

why 2 when when supposed 50/1 , 3/1 ? if ide let me return num , den @ same time, have fixed it?

thanks

java has no native way of doing this, can return 1 object or primitive. leaves 2 options:

  • return array length 2.

    public int[] reduce() {     ...     return new int[]{num, den}; } 
  • return object of wrapper class containing 2 numbers.

    public fraction reduce() {     ...     return new fraction(num, den); } 

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -