[英]Nested do-while and System.in.read() example in Java book
此處的“ ignore”變量在內部執行什么操作? 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);
}
}
正如評論中提到的, do/while
循環基本上是丟棄其余行的一種方式。 否則,程序將繼續讀取用戶在第一個字符(包括新行,這顯然是意外行為)之后放置的所有垃圾。
變量名稱ignore
可能是由於這些字符被忽略的事實所致。
基本上,這是正在發生的事情:
"Guess letter btwn AZ: "
"Input"
后接新行 'I'
並將其放入ch
變量 "Input"
循環並讀取n
, p
, u
和t
。 由於這些都不是換行符,因此它將繼續循環。 \\n
。 這打破了循環。 下次該程序調用read
,由於沒有更多數據(此時用戶可能輸入了更多數據,但無論如何),它將得到-1
。 從理論上講,該程序可以使用while(ignore!=-1)
並且同樣正確(並且可能更健壯)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.