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

查看:322
本文介绍了为什么这个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(); 为您提供char。因此,当您输入1时,它会为您提供其char值49.因此您无法输入带有输入数字的整数5。所以改变你的阅读方法。你可以使用扫描仪

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天全站免登陆