Java中的Rolling Dice循环程序

时间:2019-07-16 23:10:17

标签: java

我正在尝试编写Rolling Dice程序。 10次​​后如何停止循环?

它需要返回计算机获胜,用户获胜还是平局的次数。

当循环结束时,我如何打印谁赢得了总冠军?

    public static void main(String[] args)
    {

        int die1=(int)(Math.random()*6+1);
        int die2=(int)(Math.random()*6+1);

        int comp_wins = 0;
        int user_wins = 0;
        int tie = 0;
        int count = comp_wins + user_wins + tie;

        while (count < 11)
        {
            if (die1 > die2)
            {
                comp_wins++;
                System.out.println ("Computer Wins: " + comp_wins);
            }
            if (die2 > die1)
            {
                user_wins++;
                System.out.println ("User Wins: " + user_wins);
            }
            else
                tie++;
                System.out.println ("Ties: " + tie);
        }       

        System.out.println ("The" + "wins overall!");
    }

1 个答案:

答案 0 :(得分:0)

您快到了。您只需要掷骰子并在count循环内而不是之前增加while

要显示谁获胜,可以在comp_wins语句中比较computer_winsif


更新我的答案: 您在for循环之前设置die1和die2的值:这就是为什么同一玩家每次都获胜的原因。实际上,您要掷骰子一次,然后检查骰子十次。 (尝试通过在System.out.println(die1 + " " + die2);循环中添加for来为自己进行验证;这是调试自己的代码的有用方法。)

您只需要将“骰子滚动”移动到for循环中即可:

  public static void main(String[] args) {

    final int MAXSTOPCOUNT = 10;
    int comp_wins = 0;
    int user_wins = 0;
    int tie = 0;

    for (int i = 0; i < MAXSTOPCOUNT; i++) {
      int die1 = (int) (Math.random() * 6 + 1);
      int die2 = (int) (Math.random() * 6 + 1);

      if (die1 > die2) {
        comp_wins++;
        System.out.println("Computer Wins: " + comp_wins);
      } else if (die1 < die2) {
        user_wins++;
        System.out.println("User Wins: " + user_wins);
      } else {
        tie++;
        System.out.println("Ties: " + tie);
      }

    }

    if (comp_wins > user_wins)
      System.out.println("The computer wins overall!");
    else
      System.out.println("The user wins overall!");
  }