java - 我如何让骰子继续重新滚动和打印,直到它达到 "7"或 "point"

标签 java

我正在尝试构建一个双骰子游戏,其中计算机自动掷一对骰子,如果掷出的是 7 或 11,则用户获胜。然而,如果用户掷出 2、3 或 12,他们将自动失败。

此外,如果用户掷出任何其他数字(4、5、6、8、9、10),这就是他们的“点”,他们将尝试再次掷出该点。 (除非他们掷出 7,否则他们就输了。)如果计算机掷出 7 或“点”以外的数字,我试图让我的 while 循环继续滚动

不幸的是,我的循环不起作用并且它不会继续重新滚动。

提前致谢,这是我的代码:

这就是我现在拥有的:

public class CrapsPractice{
    public static void main(String[]args){   

        int d1 = (int) (6 * Math.random() + 1);
        int d2 = (int) (6 * Math.random() + 1);
        int roll = (d1 + d2);
        int point = roll; 

        if (roll == 7 || roll == 11) 
        {
            System.out.println("You rolled a" + roll); 
            System.out.println("Congrats! You've immediately won!");
            return; //terminate the main function
        }

        else if (roll == 2 || roll == 3 || roll == 12)
        {
            System.out.println("you rolled a " + roll);
            System.out.println("You lose!");
            return; //terminate the main function
        }

        //do-while loop: execute and then check for condition
        //and then if condition holds, execute a second time and so on
        do {
            int d3 = (int) (6 * Math.random() + 1);
            int d4 = (int) (6 * Math.random() + 1);
            roll = d3 + d4;

            System.out.println("your point is" + point);

        } while(roll != 7 && roll != point );
    }
}

最佳答案

您的代码对我有用,但请尝试这些打印输出,以更好地了解正在发生的情况:

//do-while loop: execute and then check for condition
//and then if condition holds, execute a second time and so on
do {
    int d3 = (int) (6 * Math.random() + 1);
    int d4 = (int) (6 * Math.random() + 1);
    roll = d3 + d4;

    System.out.println("your roll is " + roll + " and point is " + point);

} while(roll != 7 && roll != point );

if (roll == 7) 
    System.out.println("you lose");
else
    System.out.println("you win");

输出:

your roll is 6 and point is 9
your roll is 4 and point is 9
your roll is 3 and point is 9
your roll is 8 and point is 9
your roll is 8 and point is 9
your roll is 6 and point is 9
your roll is 9 and point is 9
you win
BUILD SUCCESSFUL (total time: 0 seconds)

关于java - 我如何让骰子继续重新滚动和打印,直到它达到 "7"或 "point",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58071773/

相关文章:

java - 为什么又要强制转换SSLServerSocketFactory?

java - 如何在 Apache Spark 中为两个具有不同结构的 DataFrame 实现 NOT IN

java - StaxEventItemReader 中的 ClassCastException

java - 覆盖仅在 Android 中的前 2 个 GPS 点之间画线

java - 安卓光束 : suppress "Tab to beam"

java - 类似@TestedOn 的理论但可用于字符串?或者单独的参数化类?

java - 自定义卸载程序无法在 Java 中自毁

java - 从具有不同高度的表格行中提取 pdf 文本(使用 pdfbox 库的 java)

java类型安全:not parameterized generic type effect on performance

java - 调用属于包的 main()