使用 Java 的控制台输入和 ENTER 键

Console input and ENTER key with Java

我正在学习 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 问题。其中用户没有检查不必要的字符并得到了意外的输出。

您可以轻松地利用 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;
    }
}