简体   繁体   中英

JAVA: How can a nested do-while loop discard characters from the input buffer?

I'm working my way through Oracle's "Java: A Beginner's Guide" and I am stumped by a subsection about using nested do-while loops. The example given creates a simple guessing game where the user inputs a letter between A and Z. If he guesses correctly the program returns "Right", otherwise additional code is executed and a hint is given -- it either returns "too high" or "too low".

The author states that he is using a nested do-while loop to "discard any other characters in the input buffer".

When I run the program without the nested do-while, whether I input a character greater than the answer that is being searched for or less than the answer that is being searched for, the program always evaluates it as being less than the answer. When I run the program with the nested do-while, the program runs correctly.

My Question: I don't understand how the nested do-while is affecting the rest of the program. What exactly is the nested do-while doing that the outer do-while isn't?

Here's the code:

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

        char ch, ignore, answer = 'K';

        do {
            System.out.println("I'm thinking of a number between A and Z");
            System.out.println("Can you guess it: ");
            ch = (char) System.in.read();


            do {
                ignore = (char) System.in.read();
            } while(ignore != '\n');

            if(ch == answer) System.out.println("Right");
            else {
                System.out.println("Sorry, you're ");
                if(ch < answer) System.out.println("too low.");
                else System.out.println("too high.");
                System.out.println("Try again!\n");
            }
        } while(answer != ch);
    }
}

The inner do-while reads a character, compares it to a newline; if it is not a newline, it reads the next character. If you enter abcde, 'a' will end up in the var ch (due to the read in the outer do loop), bcde will all be discarded, and the newline will terminate the inner loop.

If you want analysis of specific inputs, then provide the inputs.

The inner do-while is used just to be sure that you are reading the first character of the input and no more. Because as you see, it starts reading character by character until it finds '\\n', and that's like pressing "Enter". So there the program will stop reading your input (Or maybe better, will clear the buffer for future inputs) and the compared input will be truthful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM