首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >控制台输入并使用Java输入键

控制台输入并使用Java输入键
EN

Stack Overflow用户
提问于 2015-07-03 10:17:22
回答 2查看 2.6K关注 0票数 0

我正在用一本书学习Java : Java。乞丐向导。这本书展示了以下例子:

代码语言:javascript
复制
// 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);
    }
}

下面是一个示例运行:

代码语言:javascript
复制
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:

我认为这个程序的输出应该是:

代码语言:javascript
复制
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,你就太高了。我不知道为什么要换个新的系列。当它被抹去时。谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-07-03 10:41:50

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

实际上只读一个字符。

如果输入是- a\n,则只读取第一个字符并将其存储在ch中。在本例中是a

代码语言:javascript
复制
 do {
    ignore = (char) System.in.read();
     } while (ignore != '\n');

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

他们为什么要用这个?

我们只需要一封信。

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

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

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

,如果只按Enter(\n)按下

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

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

票数 1
EN

Stack Overflow用户

发布于 2015-07-03 11:01:56

相反,您可以轻松地使用Scanner

替换

代码语言:javascript
复制
// read a character
ch = (char) System.in.read();

// discard any characters in the input buffer
do {
    ignore = (char) System.in.read();
} while (ignore != '\n');

使用

代码语言:javascript
复制
Scanner in = new Scanner(System.in); //outside your loop
while(true) {
    String input = in.nextLine();
    if(!input.isEmpty()) {
        ch = input.charAt(0);
        break;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31204309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档