简体   繁体   中英

Nested do-while and System.in.read() example in Java book

What is the inner do-while with the 'ignore' variable doing here? New to Java and can't seem to understand what's happening here, or why it was included in the example?

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

        char ch, ignore, answer = 'K';

        do {
            System.out.println("Guess letter btwn A-Z: ");

            ch = (char) System.in.read();

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

            if (ch == answer) System.out.println("**RIGHT**");
            else {
                System.out.print("...Sorry, you're ");
                if(ch < answer) System.out.println("too low");
                else System.out.println("too hight");
                System.out.println("try again!\n");
            }
        } while (answer != ch);
    }
}

As was mentioned in the comments, the do/while loop is basically a way to discard the rest of the line. Otherwise, the program would continue reading whatever garbage the user put after the first character (including the new line, which would obviously be unexpected behavior).

The variable name ignore is probably due to the fact that these characters are being ignored.

Basically, here's what's happening:

  • Program Prints "Guess letter btwn AZ: "
  • User inputs "Input" followed by a new line
  • Program grabs 'I' and puts it into ch variable
  • Program loops through "Input" and reads n , p , u , and t . Since none of these are the new line character, it continues it's loop.
  • Program reads \\n . This breaks the loop. Next time the program calls read , it will get -1 as there is no more data (at that point the user could have inputted more data, but whatever).

Theoretically, the program could have used a while(ignore!=-1) and been equally correct (and possibly a little more robust).

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