1

我的程序目标是首先从 1-6 生成一个随机数,称为“点”,然后用户将继续输入一个键来重新掷出相应的“骰子”,如果掷出相同的数字,用户应该提示来自第一个 if 语句的消息

但是,无论何时掷下一个骰子,它都不会滚到点数上,并且第一个 if 语句打印行会随机打印出来。关于如何解决这个问题的答案将不胜感激?

import java.io.*;

public class DiceGame1
{
  public static void main (String [] args) throws IOException
  {

    String userInput;
    int DiceRoll;
    int exit = 0;


    BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
    System.out.println("Hello, this program rolls a dice and outputs the number rolled");

    System.out.println("The number rolled is called the point it will keep rolling untill it");
    System.out.println("hits that point again, press any key to con't");

    userInput = myInput.readLine();

    DiceRoll = (int) (Math.random () *(6-1) + 1);

    System.out.println("The point to match is: " + DiceRoll);
    System.out.println("Press any key to roll again...");
    userInput = myInput.readLine();

    while(exit != 999) {
      int nextRoll = (int) (Math.random () *(6-1) + 1);

      if (nextRoll == DiceRoll)
      {
        System.out.println(" It took the computer _____ tries to reach the point");
      }
      else 
      {
        System.out.println("The roll is : " + nextRoll);
        System.out.println("Press any key to roll again...Or press '999' to exit");
        userInput = myInput.readLine();
      }  
    }
  }
}
4

2 回答 2

2

您的循环退出条件是exit == 999. exit但是您永远不会在循环中分配任何值。所以它无限循环。

In addition, you only print the value of the dice when it's not equal to the first roll. And not when it is. So you got the impression that the first message is printed when it shouldn't.

于 2013-03-04T22:31:19.850 回答
1

I think what you are looking for to do is to always have to roll the dice, even if it is a match. You can accomplish that by removing the print and input to outside of the else clause, as such:

  if (nextRoll == DiceRoll)
  {
    System.out.println(" It took the computer _____ tries to reach the point");
  }
  else 
  {
    System.out.println("The roll is : " + nextRoll);
  }  
   System.out.println("Press any key to roll again...Or press '999' to exit");
   userInput = myInput.readLine();

Besides, you will never get a DiceRoll or NextRoll that is 6 - (int) Math.random()*5+1 = (int) (0-.999)*5+1 = (int) (0-4.999)+1 = (int) 1-5.999 = 1-5. The cast to int will round downwards, so you will need (int) Math.random()*6+1 instead.

于 2013-03-04T22:35:50.000 回答