java方法 返回两个值,如何从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);

}

Error:

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 Result: 1

解决方案

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.

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());

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值