为什么这个 do-while 循环不能产生正确的输出? [英] Why does this do-while loop not produce the right output?

查看:39
本文介绍了为什么这个 do-while 循环不能产生正确的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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,那么他们就猜到了这个数字.如果不是,那么他们还没有猜到这个数字.这就是游戏的前提.有人可以帮我修复我的代码,因此无论如何它都不会输出相同的内容吗?

So here I wrote some code. It's supposed to be a guessing game, but no matter what I input, it always gives me in the output "Please input a number..." NO MATTER WHAT I PUT. Basically, if the "guess" is more than 5, then they guessed the number. If it's not, then they haven't guessed the number. That's the premise of the game. Can someone help me fix my code, so it doesn't just output the same thing regardless?

推荐答案

System.in.read(); 为您提供字符.因此,当您输入1"时,它会为您提供其字符值 49.因此您无法通过键入数字输入整数 5.所以改变你的阅读方法.你可以使用 Scanner

System.in.read(); gives you char. so when you enter "1", it gives you its char value, 49. so you can not enter integer 5 with typing numbers. so change your reading method. you can use Scanner

这篇关于为什么这个 do-while 循环不能产生正确的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆