如何从 Java 方法返回 2 个值? [英] How to return 2 values from a Java method?
问题描述
我试图从 Java 方法返回 2 个值,但出现这些错误.这是我的代码:
I am trying to return 2 values from a Java method but I get these errors. Here is my code:
// 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
推荐答案
与其返回包含两个值的数组或使用通用的 Pair
类,不如考虑创建一个表示结果的类你想返回,并返回该类的一个实例.给班级起一个有意义的名字.与使用数组相比,这种方法的优点是类型安全,并且会使您的程序更易于理解.
Instead of returning an array that contains the two values or using a generic Pair
class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.
注意:一个通用的 Pair
类,正如这里其他一些答案中所提议的,也为您提供了类型安全,但没有传达结果代表什么.
Note: A generic Pair
class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.
示例(不使用真正有意义的名称):
Example (which doesn't use really meaningful names):
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());
}
这篇关于如何从 Java 方法返回 2 个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!