如何从Java方法返回2个值?我试图从Java方法返回2个值但我得到这些错误。这是我的代码:// Method codepublic static int something(){ int number1 = 1; int number2 = 2; return number1, number2;}// Main method codepublic static void main(String[] args) { something(); System.out.println(number1 + number2);}错误:Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement at assignment.Main.something(Main.java:86) at assignment.Main.main(Main.java:53)
3 回答

万千封印
TA贡献1891条经验 获得超3个赞
不要返回包含这两个值或使用泛型Pair
类的数组,而应考虑创建一个表示要返回的结果的类,并返回该类的实例。给这个班一个有意义的名字。与使用阵列相比,这种方法的好处是类型安全,它将使您的程序更容易理解。
注意:Pair
这里的一些其他答案中提出的泛型类也为您提供类型安全性,但不传达结果所代表的含义。
示例(不使用真正有意义的名称):
final class MyResult { private final int first; private final int second; public MyResult(int first, int second) { this.first = first; this.second = second; } public int getFirst() { return first; } public int getSecond() { return second; }}// ...public static MyResult something() { int number1 = 1; int number2 = 2; return new MyResult(number1, number2);}public static void main(String[] args) { MyResult result = something(); System.out.println(result.getFirst() + result.getSecond());}

aluckdog
TA贡献1847条经验 获得超7个赞
Java不支持多值返回。返回一组值。
// Function code
public static int[] something(){
int number1 = 1;
int number2 = 2;
return new int[] {number1, number2};
}
// Main class code
public static void main(String[] args) {
int result[] = something();
System.out.println(result[0] + result[1]);
}

繁花不似锦
TA贡献1851条经验 获得超4个赞
Pair
如果您确定只需要返回两个值,则可以实现泛型:
public class Pair<U, V> { /** * The first element of this <code>Pair</code> */ private U first; /** * The second element of this <code>Pair</code> */ private V second; /** * Constructs a new <code>Pair</code> with the given values. * * @param first the first element * @param second the second element */ public Pair(U first, V second) { this.first = first; this.second = second; }//getter for first and second
然后让方法返回Pair
:
public Pair<Object, Object> getSomePair();
添加回答
举报
0/150
提交
取消