[英]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: 基本上,这是正在发生的事情:
"Guess letter btwn AZ: "
"Guess letter btwn AZ: "
"Input"
followed by a new line "Input"
后接新行 'I'
and puts it into ch
variable 'I'
并将其放入ch
变量 "Input"
and reads n
, p
, u
, and t
. "Input"
循环并读取n
, p
, u
和t
。 Since none of these are the new line character, it continues it's loop. \\n
. \\n
。 This breaks the loop. 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.