Is it possible to return more than one value from a method in Java?(是否可以从 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]
这篇关于是否可以从 Java 中的方法返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以从 Java 中的方法返回多个值?
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01