使用Java控制台输入和ENTER键

时间:2015-07-03 10:17:23

标签: java console-application

我正在学习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! 

在&#39; a&#39;之间没有\ n并且&#39; ...对不起,你太高了#39;我不知道为什么会出现一条新线。这样做会抹去它。 谢谢。

2 个答案:

答案 0 :(得分:1)

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问题。其中用户没有检查不必要的字符并获得意外的输出。

答案 1 :(得分:0)

相反,使用char-by-char,您可以轻松使用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;
    }
}