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 中的方法返回多个值?


- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01