我正在通过这本书学习 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' 和 '...抱歉,你太高了' 之间没有\n。我不知道为什么会出现一条新线。 do-while 会删除它。 谢谢。
最佳答案
ch = (char) System.in.read();
实际上读取一个字符。
如果输入是 - a\n
,则仅读取第一个字符并将其存储在 ch
中。在本例中是 a
。
do {
ignore = (char) System.in.read();
} while (ignore != '\n');
这用于删除任何不需要的字符。
他们为什么使用这个?
我们只需要一个字母。
因此,如果用户给出的输入不是单个字符,例如“example”,并且您的代码没有循环检查。
首先,ch
变为 e
,然后 x
....依此类推。
即使用户没有输入字母表,之前的输入也被视为已输入。
如果只按下 Enter(\n) 会怎样
即使 \n
也被视为字符,它也会被读取。比较时考虑其ASCII值。
看看this问题。其中用户没有检查不必要的字符并得到了意外的输出。
关于java - Java 的控制台输入和 ENTER 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31204309/