Java do-while循环跳过控制台输入 [英] Java do-while loop skipping console input

查看:467
本文介绍了Java do-while循环跳过控制台输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Noob1 {
    public static void main(String args[]) 
        throws java.io.IOException{

        char ch, answer;
        answer = 'g';

        do {
            System.out.println("Guess from A-L:");
            ch = (char) System.in.read();
                if(ch == answer){
                    System.out.println("Congratz!");
            } else System.out.println("Try again!");
        } while (ch != answer);
    }
}

输出为:

Guess from A-L:
a
Try again!
Guess from A-L:
Try again!  // this is where intuitively it should ask for input again
Guess from A-L:
Try again!
Guess from A-L:
g           //  input is skipped a few times
Congratz!

我无法弄明白为什么,我正在为初学者读一本书,一切都应该被覆盖,我缺少什么?

I cannot figure out why, I'm reading a book for beginners and everything should've been covered, what am I missing?

在循环结束时添加下面的代码确认它正在循环但输入以某种方式被跳过。

Adding the code below at the end of the loop confirms that it is being looped but the input is somehow skipped.

i++;
System.out.println(i);

所以我用它来工作:

import java.io.*;

class Noob1 
{
    public static void main(String args[]) throws java.io.IOException
    {
        char ch, answer;
        String tmp;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        answer = 'g';

            do 
            {
                System.out.println("Guess character followed by ENTER:");
                tmp = bufferedReader.readLine();
                ch = tmp.charAt(0); // only first char is considered
                if (ch == answer) 
                    System.out.println("Gratz! the answer was: " + ch + "!");
                else 
                    System.out.println("Nope, try again..");
            } while (ch != answer);
    }
}

格式是否仍然可怕?

推荐答案

读取只读取一个字符,但在回答时,您输入的内容超过一个字符:您正在键入 a 后跟换行符,因为在您按Enter键之前,控制台输入不会发送到流。该换行位于流中,等待下一个读取读取,这就是为什么它不等你再输入一些内容。

read only reads a single character, but when answering, you're typing more than one character: You're typing a followed by a newline, because console input doesn't get sent to the stream until you press Enter. That newline sits there in the stream waiting to be read by the next read, which is why it doesn't wait for you to type something again.

您可能希望在 BufferedReader 中包装 System.in 并使用 BufferedReader #readLine 并处理你得到一个字符串而不是一个字符的事实,或者在获得你的角色之后,反复调用读取直到你获得换行符。我选择 bufferedReader

You may want to wrap System.in in a BufferedReader and use BufferedReader#readLine and handle the fact you get a string instead of one character, or alternately after getting your character, call read repeatedly until you get the newline. I'd opt for bufferedReader.

这篇关于Java do-while循环跳过控制台输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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