【问题标题】:Why does this do-while loop not produce the right output?为什么这个 do-while 循环不能产生正确的输出?
【发布时间】:2014-12-04 16:05:41
【问题描述】:
public static void main(String[] args) throws IOException {

    System.out.println("Hello, come and play a game with me!");

    int x = 5;
    int guess;

    do {
        System.out.println("Please input a number...");
        guess = System.in.read();
        guess = System.in.read();
        if (guess < 5) {
            System.out.println("You guessed the number!");
            break;
        }
    } while (guess > 5);
}

所以我在这里写了一些代码。它应该是一个猜谜游戏,但无论我输入什么,它总是在输出中给我“请输入一个数字......”无论我输入什么。基本上,如果“猜测”超过 5 个,那么他们就猜到了这个数字。如果不是,那么他们还没有猜到这个数字。这就是游戏的前提。有人可以帮我修复我的代码,这样它就不会输出相同的东西吗?

【问题讨论】:

  • 您是否尝试调试以查看guess 在执行期间具有哪些值?
  • 1) 为什么要输入两次猜测?如果guess 小于 5,还要查看你的 if 语句,那么你正在打破
  • 删除第二个System.in.read(),将- '0'添加到第一个。

标签: java loops while-loop output


【解决方案1】:

System.in.read(); 给你字符。因此,当您输入“1”时,它会为您提供其 char 值 49。因此您不能在输入数字时输入整数 5。所以改变你的阅读方法。你可以使用Scanner

【讨论】:

  • 这解决了我的问题!我使用了 Rami 的代码,并用 Scan 替换了 Buffer,它的工作方式就像我所知道的格式和代码的魅力!谢谢大家!
【解决方案2】:

您正在做相反的事情 - 小于 5 的答案被认为是正确的。

【讨论】:

    【解决方案3】:

    这是您的代码的工作版本。

    如前面的答案所述,System.in 读取字符,因此您无法直接读取数字。下面的代码利用了 BufferedReader API,它在 InputStream 上工作。

    public class App {
    
    
            public static void main(String[] args) throws IOException {
    
                    System.out.println("Hello, come and play a game with me!");
    
                    int x = 5;
                    int guess;
    
                    do                
                    {               
                        System.out.println("Please input a number...");
                       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
                       guess = Integer.parseInt(br.readLine());
                        if(guess < 5){
    
                            System.out.println("You guessed the number!");                    
                            break;                    
                        }
    
                    } while(guess>5);        
             }    
        }
    

    【讨论】:

      【解决方案4】:

      您似乎没有使用变量 x,请尝试使用 Scanner 类从用户那里获取输入

      public static void main(String[] args) 抛出 IOException {

      System.out.println("Hello, come and play a game with me!");
       int guess;
       Scanner input = new Scanner(System.in);
      
      
      
      do {
          System.out.println("Please input a number...");
           guess = input.nextInt();
                 if (guess < 5) {
              System.out.println("You guessed the number!");
              break;
          }
      } while (guess > 5);
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-26
        • 1970-01-01
        • 2016-07-14
        • 1970-01-01
        相关资源
        最近更新 更多