Java如何返回两个变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21591178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:32:42  来源:igfitidea点击:

Java how to return two variables?

javareturn

提问by UniQuadrion

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

在 C++ 之后,我正在尝试学习一些 Java,并且我对我一直在研究的代码有疑问。我正在学习分数课程,但我陷入了减少部分。由于该方法不允许我同时返回“num”和“den”,我不得不返回“n”这是我的方法

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.

我正在尝试“返回 num,den;” 但是它不允许我。

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?

为什么我应该得到 50/1 和 3/1 时得到 2?如果 IDE 让我同时返回 num 和 den,那会解决它吗?

Thanks

谢谢

采纳答案by Martijn Courteaux

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

Java 没有这样做的本地方式,您只能返回一个Object或原语。这给您留下了两个选择:

  • 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);
    }
    
  • 返回一个长度为 2 的数组。

    public int[] reduce()
    {
        ...
        return new int[]{num, den};
    }
    
  • 返回包含两个数字的包装类的对象。

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

回答by rgettman

It looks like your reducemethod 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 Fractionin the declaration.

看起来您的reduce方法正在修改对象。目前还不清楚你到底想返回什么。如果您希望分数返回自身,则return this;,该方法Fraction在声明中返回 a 。