【发布时间】:2015-07-03 10:17:22
【问题描述】:
我正在通过这本书学习 Java:Java。初学者指南。 本书展示了以下示例:
// Guess the letter game, 4th version.
class Guess4 {
public static void main (String args[])
throws java.io.IOException {
char ch, ignore, answer = 'K';
do {
System.out.println ("I'm thinking of a letter between A and Z.");
System.out.print ("Can you guess it: ");
// read a character
ch = (char) System.in.read();
// discard any characters in the input buffer
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 high");
System.out.println ("Try again!\n");
}
} while (answer != ch);
}
}
这是一个示例运行:
I'm thinking of a letter between A and Z.
Can you guess it: a
...Sorry, you're too high
Try again!
I'm thinking of a letter between A and Z.
Can you guess it: europa
...Sorry, you're too high
Try again!
I'm thinking of a letter between A and Z.
Can you guess it: J
...Sorry, you're too low
Try again!
I'm thinking of a letter between A and Z.
Can you guess it:
我认为程序的输出应该是:
I'm thinking of a letter between A and Z.
Can you guess it: a...Sorry, you're too high
Try again!
在 'a' 和 '...Sorry, you are too high' 之间没有 \n。我不知道为什么会出现一个新行。 do-while 将其删除。 谢谢。
【问题讨论】:
-
更改书 :) - 使用:Head First Java - oReally
-
\n也被认为是一个字符,所以我们需要在字母游戏中跳过它,因此需要 do while 循环