问题
我试图从Java方法返回2个值但我得到这些错误。这是我的代码:
// Method code
public static int something(){
int number1 = 1;
int number2 = 2;
return number1, number2;
}
// Main method code
public 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)
Java结果:1
#1 热门回答(188 赞)
不要返回包含这两个值的数组或使用genericPair
class,而应考虑创建一个表示要返回的结果的类,并返回该类的实例。给这个类一个有意义的名字。与使用阵列相比,这种方法的好处是类型安全,它将使你的程序更容易理解。
注意:这里的一些其他答案中提出的genericPair
class也为你提供了类型安全性,但没有传达结果所代表的含义。
示例(不使用真正有意义的名称):
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());
}
#2 热门回答(59 赞)
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]);
}
#3 热门回答(31 赞)
如果你确定只需要返回两个值,则可以实现genericPair
:
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();