【问题标题】:Console input and ENTER key with JavaJava 的控制台输入和 ENTER 键
【发布时间】: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 循环

标签: java console-application


【解决方案1】:

ch = (char) System.in.read();

实际上读取一个字符。

如果输入是 - a\n,则仅读取第一个字符并将其存储在 ch 中。在这种情况下是a

 do {
    ignore = (char) System.in.read();
     } while (ignore != '\n');

这用于删除任何不需要的字符。

他们为什么使用这个?

我们只需要一个字母。

因此,如果用户输入的不是单个字符,例如“示例”,并且您的代码没有循环检查。

首先ch 变成e,然后是x ....等等。

即使用户没有输入字母,之前的输入也被认为是输入的。

如果只按下 Enter(\n) 会怎样

即使\n 被认为是一个字符,它也会被读取。在比较中考虑了它的ASCII值。

看看this 的问题。其中用户没有检查不必要的字符并得到意外的输出。

【讨论】:

  • 谢谢。但我认为程序的输出应该是:
  • 我在想 A 和 Z 之间的一个字母。你能猜到吗:a...对不起,你太高了再试一次!在 'a' 和 '...Sorry, you are too high' 之间没有 \n。我不知道为什么要换行。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    相关资源
    最近更新 更多