是否可以从 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();
它被赋予与游戏状态相同的值...一个 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]
相关文章