java - 尝试随机掷两个骰子并将总和相加直至达到二十一

标签 java loops class methods program-entry-point

我正在尝试编写一个程序,随机掷两个骰子,将它们加在一起,并继续这样做,直到达到 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/

相关文章:

java - 7'' 平板电脑的 android xlarge 布局

C++:以对角线方式处理二维数组元素

c++ - 设置要与无序集一起使用的自定义类 - 在集合中找不到元素

java - 获取运行时提供的类名的 n 维数组的类

Java - 在其自己的类中引用对象数据?

java - 如何安全退出 lib gdx 应用程序?

java - 重新启动 Clip 对象 - flush() 方法

java - 使用 Java Swing 和 JEditorPane 将标记的文本设为粗体

arrays - 退出代码 101 使用 &array 遍历数组

c - Lua脚本: embed C code to run automatically at the start of a while loop