【问题标题】:Java: Rolling two dice until you get a desired sumJava:掷两个骰子,直到得到所需的总和
【发布时间】:2018-01-16 19:33:05
【问题描述】:

我想编写一个程序,让我掷两个骰子,直到我得到这些骰子的总和为 11。我想记录在我得到总和时我使用了多少“尝试”或掷骰子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 做同样的事情。然后,尝试次数较少的玩家“赢得”游戏。

帮助感谢我是新手

【问题讨论】:

  • 你的条件不对,应该是while (P1sum != 11)而不是while (P1sum == 11)

标签: java dice


【解决方案1】:

考虑一下,Math.random() 返回浮点数 0 <= x <= 1.0 (Java API docs Math.random())。所以,你的公式的最大值:

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

等于 7。

【讨论】:

    【解决方案2】:

    您可能想要更新您的状况

    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
    

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 2021-04-04
      相关资源
      最近更新 更多