首页 > 解决方案 > 我怎样才能让骰子继续重新滚动和打印,直到它达到“7”或“点”

问题描述

我正在尝试构建一个掷骰子游戏,其中计算机自动掷出一对骰子,如果掷出的骰子是 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 );
    }
}

标签: java

解决方案


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

//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)

推荐阅读