如何在java中使用scanner类捕获空白输入 [英] how to catch blank input with scanner class in java

查看:883
本文介绍了如何在java中使用scanner类捕获空白输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用scanner类从命令行捕获用户输入(仅限字符串),作为我之前的替代问题

I am using the scanner class to capture user input from the command line (strings only), as an alternative to my previous question.

以下似乎工作正常,除了空白行没有按照第二个条件被抓住。例如,当我按Enter键时,应将其捕获为空行,第二个条件应为true。然而,每次在控制台上都会显示一个新的空白行,如果我继续按Enter键,整个控制台向上滚动,而不是条件中的逻辑。

The following seems to work fine, except the blank lines are not caught as they should by the second conditional. For example when I press enter, this should be captured as a blank line and the second conditional should be true. However a new blank line is displayed on the console everytime, with the entire console "scrolling" upward if I keep hitting enter, rather than the logic in the conditional.

是有一种正确的方法来使用扫描仪从命令行捕获空白输入? (有人点击进入,或多次击中空间然后进入)

Is there a proper way to catch a blank input from the command line using scanner? (someone hitting just enter, or hit space a few times and then enter)

感谢您的任何建议

Machine aMachine = new Machine();
String select;
Scanner br = new Scanner(System.in); 
 while(aMachine.stillInUse()){
  select = br.next();
        if (Pattern.matches("[rqRQ1-6]", select.trim())) {
        aMachine.getCommand(select.trim().toUpperCase()).execute(aMachine);
        }
        /*
         * Ignore blank input lines and simply
         * redisplay current status -- Scanner doesn't catch this
         */
        else if(select.trim().isEmpty()){
        aMachine.getStatus();

        /*
         * Everything else is treated
         * as an invalid command
         */
    else {                
            System.out.println(aMachine.badCommand()+select);
            aMachine.getStatus();
        }
    }


推荐答案

扫描程序是用于输入的文件I / O的for dummies实现。它允许教程和教科书编写者编写演示代码而不用担心它的复杂性。

Scanner is a "for dummies" implementation of file I/O for input. It allows tutorial and textbook writers to write demo code without moaning about the complications of it.

如果你真的想知道你在读什么,你必须说些什么喜欢

If you really want to know what you're reading, you have to say something like

BufferedReader br = new BufferedReader(new FileReader("myfile.txt"))

...然后你可以做到

...and then you can do

String line = br.readLine()

除了事实之外别无其他。

and see nothing but the truth.

这篇关于如何在java中使用scanner类捕获空白输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆