我正在尝试编写一个程序,随机掷两个骰子,将它们加在一起,并继续这样做,直到达到 21。如果达到 21,则获胜,但如果超过 21,则失败。
这就是我到目前为止所拥有的,如果我能就如何正确滚动骰子获得一些帮助,那就太好了。我是 java 初学者,所以仍在尝试理解语法。
import java.util.Random;
public class TwentyOne{
public static void main(String[] args) {
int dice1;
int dice2;
welcome();
rollingDice(int dice1,int dice2);
}
public static void welcome() {
System.out.println("Welcome to the game of Twenty-One! FEELING LUCKY?! goodluck!");
}
public static int rollingDice(int dice1, int dice2) {
dice1 = (int)(Math.random()*6 + 1);
dice2 = (int)(Math.random()*6 + 1);
int sum = dice1 + dice2;
return sum;
}
}
最佳答案
正如@KamalNayan 上面所说,您需要循环rollingDice 直到达到或高于21,并且不需要将int 参数传递到rollingDice 方法,因为滚动骰子值是在该方法的范围内生成的。一些正在发生的事情的打印也有助于演示运行时发生的事情:
public static void main(String[] args) {
welcome();
int total = 0;
while (total < 21) {
total += rollingDice();
};
System.out.println("Total for all rolls was: " + total);
if (total == 21) {
System.out.println("You win!");
}
else {
System.out.println("You lose.");
}
}
public static void welcome() {
System.out.println("Welcome to the game of Twenty-One! FEELING LUCKY?! goodluck!");
}
public static int rollingDice() {
int dice1 = (int) (Math.random() * 6 + 1);
int dice2 = (int) (Math.random() * 6 + 1);
int sum = dice1 + dice2;
System.out.println(String.format("dice1: %d dice2: %d for a total: %d", dice1, dice2, sum ));
return sum;
}
这是获胜游戏的输出:
Welcome to the game of Twenty-One! FEELING LUCKY?! goodluck!
dice1: 4 dice2: 1 for a total: 5
dice1: 1 dice2: 4 for a total: 5
dice1: 1 dice2: 3 for a total: 4
dice1: 6 dice2: 1 for a total: 7
Total for all rolls was: 21
You win!
进程已完成,退出代码为 0
关于java - 尝试随机掷两个骰子并将总和相加直至达到二十一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49890443/