是否可以从Java中的方法返回多个值? [英] Is it possible to return more than one value from a method in Java?
问题描述
我正在使用模拟器来玩掷骰子而我正试图从同一种方法中返回两个值(或者更确切地说,我想)。
I am using a simulator to play craps and I am trying to return two values from the same method (or rather I would like to).
当我写的时候我的回复陈述我只是试着把&编译和运行正常;但我无法访问第二个返回值。
When I wrote my return statement I simply tried putting "&" which compiled and runs properly; but I have no way of accessing the second returned value.
public static int crapsGame(){
int myPoint;
int gameStatus = rollagain;
int d1,d2;
int rolls=1;
d1 = rollDice();
d2 = rollDice();
switch ( d1+d2 ) {
case 7:
case 11:
gameStatus = win;
break;
case 2:
case 3:
case 12:
gameStatus = loss;
break;
default:
myPoint = d1+d2;
do {
d1=rollDice();
d2=rollDice();
rolls++;
if ( d1+d2 == myPoint )
gameStatus = win;
else if ( d1+d2 == 7 )
gameStatus = loss;
} while (gameStatus == rollagain);
} // end of switch
return gameStatus & rolls;
}
当我将值返回为:
gameStatus=crapsGame();
它恰当地设定了赢或输的可变性,但是如果我尝试的东西就像跟随该声明一样简单:
It appropriately sets the varaible to win or lose but if I try something as simple as following that statement with:
rolls=crapsGame();
它被赋予与gamestatus相同的值... a 0或1(输赢) 。
我可以访问第二个返回值的任何方式吗?或者有一种完全不同的方式吗?
It is assigned the same value as gamestatus...a 0 or a 1 (win or lose). Any way that I can access the second returned value? Or is there a completely different way to go about it?
推荐答案
创建自己的值持有者对象以保存两个值,然后返回它。
Create your own value holder object to hold both values, then return it.
return new ValueHolder(gameStatus, rolls);
可以返回一个包含多个值的数组,但这是神秘的,它对可读性没有任何作用。理解这意味着什么要容易得多......
It's possible to return an array with multiple values, but that's cryptic and it does nothing for readability. It's much easier to understand what this means...
valueHolder.getGameStatus()
比这意味着什么。
intArray[0]
这篇关于是否可以从Java中的方法返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!