虽然使用if语句的循环不起作用,但它应该是(Math.random)

时间:2013-03-04 22:20:07

标签: java random

我的程序目标是首先从1-6中生成一个随机数,称为'point',然后用户将继续输入一个键以重新滚动'dice',如果滚动相同的数字应该使用第一个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();
      }  
    }
  }
}

2 个答案:

答案 0 :(得分:2)

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

此外,您只能在骰子不等于第一次掷骰时打印骰子的值。而不是它。所以你得到的印象是,第一条消息不应该被打印出来。

答案 1 :(得分:1)

我认为你要做的就是总是要掷骰子,即使它是匹配的。您可以通过删除打印并输入到else子句的外部来实现这一点,如下所示:

  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();

此外,你永远不会得到一个DiceRoll或NextRoll,它是6 - (int) Math.random()*5+1 =(int)(0-.999)* 5 + 1 =(int)(0-4.999)+1 =(int )1-5.999 = 1-5。对int的强制转换将向下舍入,因此您需要(int) Math.random()*6+1代替。