我试图从一个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
如果你确定你只需要返回两个值,你可以实现一个泛型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();
在我看来,最好是创建一个新类,其中构造函数是你需要的函数,例如:
public class pairReturn{
//name your parameters:
public int sth1;
public double sth2;
public pairReturn(int param){
//place the code of your function, e.g.:
sth1=param*5;
sth2=param*10;
}
}
然后像使用函数一样使用构造函数:
pairReturn pR = new pairReturn(15);
你可以使用pR.sth1 pR.sth2作为函数的2个结果
在Java中只能返回一个值,所以最简洁的方法是这样的:
return new Pair<Integer>(number1, number2);
这是你的代码的更新版本:
public class Scratch
{
// Function code
public static Pair<Integer> something() {
int number1 = 1;
int number2 = 2;
return new Pair<Integer>(number1, number2);
}
// Main class code
public static void main(String[] args) {
Pair<Integer> pair = something();
System.out.println(pair.first() + pair.second());
}
}
class Pair<T> {
private final T m_first;
private final T m_second;
public Pair(T first, T second) {
m_first = first;
m_second = second;
}
public T first() {
return m_first;
}
public T second() {
return m_second;
}
}