Java: 掷两个骰子直到你得到想要的总和

Java: Rolling two dice until you get a desired sum

我想写一个程序,我掷两个骰子,直到我得到这些骰子的总和为 11。我想记录我用了多少 "attempts" 或掷骰子得到 11 的总和。

到目前为止我的代码:

public class Dice {

    public static void main(String[] args) {

    int counter1 = 0; //Amount of rolls player 1 took to get sum of 9
    int P1sum = 0;

    do {
        int P1Die1 = (int)(Math.random()*6)+1;
        int P1Die2 = (int)(Math.random()*6)+1;  
        P1sum = (P1Die1 + P1Die2);
        counter1++;
    } while (P1sum == 11);

        System.out.println("Player 1 took "+counter1+" amount of rolls to have a sum of 11.");  
    }
}

它一直在打印需要 1 卷才能得到 11 的总和,所以有些不对劲。

我的目标:让玩家 1 继续滚动 2 直到我的总和为 11,并记录尝试了多少次。然后让玩家 2 做同样的事情。然后,无论哪个玩家尝试 "wins" 游戏的次数较少。

帮助感谢感谢我是新手

您可能想要更新您的条件

while (P1sum == 11) // this results in false and exit anytime your sum is not 11

while (P1sum != 11) // this would execute the loop until your sum is 11

考虑一下,Math.random() returns 浮点数 0 <= x <= 1.0 (Java API docs Math.random())。因此,公式的最大值:

(int)(Math.random()*6)+1;

等于 7。