【问题标题】:While loop with if statements does work not but as it is supposed to (Math.random)带有 if 语句的 While 循环不起作用,但它应该起作用(Math.random)
【发布时间】:2013-03-05 06:44:18
【问题描述】:

我的程序目标是首先从 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();
      }  
    }
  }
}

【问题讨论】:

  • 如果您希望我们帮助您解决此问题,我们将不胜感激。
  • 对不起,我刚刚粘贴了它,我很抱歉!
  • 您在哪里分配exit 值?你的 while 循环永远不会退出。
  • System.out.println("The roll is : " + nextRoll);?您可能希望始终这样做,而不仅仅是在 else 内。
  • 您是否尝试过使用调试器?使用控制台打印语句可能无法正确告诉您程序中发生了什么,因为 System.In 不是立即打印的。尝试使用调试器并评估您的表达式。

标签: java random


【解决方案1】:

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

此外,您仅在骰子不等于第一次掷骰时打印骰子的值。而不是什么时候。所以你的印象是,第一条消息不应该被打印出来。

【讨论】:

  • 即使有那个地方,也不能解决我的实际问题。
  • 那么考虑到这一点,有没有办法可以修复它以便打印该行?
  • 是的,就像在 else 块中一样打印它。由于您最终会在ifelse 块中得到完全相同的指令,因此您可以将这条指令移到if 块之前。代码是你真的写的,还是你从某个地方得到的而不理解它?
  • 是的,我写了代码,但是这个随机整数对我来说是全新的。
  • 所以保持 else 块不变,但将指令移到 if 块之前的 while 循环之外?
【解决方案2】:

我认为你想要做的是总是要掷骰子,即使是一场比赛。您可以通过删除 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();

此外,您永远不会得到 6 - (int) Math.random()*5+1 = (int) (0-.999)*5+1 = (int) (0-4.999)+1 = (int) 1 的 DiceRoll 或 NextRoll -5.999 = 1-5。转换为 int 将向下舍入,因此您将需要 (int) Math.random()*6+1

【讨论】:

  • 这并不能解决问题,因为第一行 if 语句仍然是随机打印的
猜你喜欢
  • 2018-03-28
  • 1970-01-01
  • 2022-01-26
  • 2013-08-16
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-03
相关资源
最近更新 更多