我正在用一本书学习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’之间的\n,你就太高了。我不知道为什么要换个新的系列。当它被抹去时。谢谢。
发布于 2015-07-03 10:41:50
ch = (char) System.in.read();
实际上只读一个字符。
如果输入是- a\n,则只读取第一个字符并将其存储在ch中。在本例中是a。
do {
ignore = (char) System.in.read();
} while (ignore != '\n');这用于删除任何不需要的字符。
他们为什么要用这个?
我们只需要一封信。
因此,如果用户给出的输入不是单个字符,比如“示例”,如果您的代码没有循环检查。
首先,ch变成e,然后是x ....so on。
即使没有用户输入字母表,前面的输入也被认为是输入的。
,如果只按Enter(\n)按下
即使是\n也被认为是一个字符,它也被读取。在比较中考虑了它的ASCII值。
看看this的问题。其中,用户没有检查不必要的字符,并得到了意外的输出。
发布于 2015-07-03 11:01:56
相反,您可以轻松地使用Scanner。
替换
// read a character
ch = (char) System.in.read();
// discard any characters in the input buffer
do {
ignore = (char) System.in.read();
} while (ignore != '\n');使用
Scanner in = new Scanner(System.in); //outside your loop
while(true) {
String input = in.nextLine();
if(!input.isEmpty()) {
ch = input.charAt(0);
break;
}
}https://stackoverflow.com/questions/31204309
复制相似问题