简体   繁体   English

Java书中的嵌套do-while和System.in.read()示例

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

What is the inner do-while with the 'ignore' variable doing here? 此处的“ ignore”变量在内部执行什么操作? New to Java and can't seem to understand what's happening here, or why it was included in the example? Java的新手,似乎无法理解这里发生的事情,或者为什么将它包含在示例中?

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. 正如评论中提到的, do/while循环基本上是丢弃其余行的一种方式。 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. 变量名称ignore可能是由于这些字符被忽略的事实所致。

Basically, here's what's happening: 基本上,这是正在发生的事情:

  • Program Prints "Guess letter btwn AZ: " 程序打印"Guess letter btwn AZ: "
  • User inputs "Input" followed by a new line 用户输入"Input"后接新行
  • Program grabs 'I' and puts it into ch variable 程序获取'I'并将其放入ch变量
  • Program loops through "Input" and reads n , p , u , and t . 程序通过"Input"循环并读取nput Since none of these are the new line character, it continues it's loop. 由于这些都不是换行符,因此它将继续循环。
  • Program reads \\n . 程序读取\\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). 下次该程序调用read ,由于没有更多数据(此时用户可能输入了更多数据,但无论如何),它将得到-1

Theoretically, the program could have used a while(ignore!=-1) and been equally correct (and possibly a little more robust). 从理论上讲,该程序可以使用while(ignore!=-1)并且同样正确(并且可能更健壮)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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