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

以下似乎工作正常,除了空行没有被第二个条件捕获。例如,当我按 Enter 时,这应该被捕获为空行,并且第二个条件应该为 true。然而,每次控制台上都会显示一个新的空行,如果我继续按 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();
        }
    }
有帮助吗?

解决方案

Scanner 是用于输入的文件 I/O 的“傻瓜式”实现。它允许教程和教科书作者编写演示代码,而无需抱怨其复杂性。

如果你真的想知道你在读什么,你必须说类似的话

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

...然后你可以做

String line = br.readLine()

只看到真相。

其他提示

选择= br.next();

...阻塞直到找到合适的令牌。这意味着它将等待直到看到令牌返回,因此您不会从中得到空行。

尝试替换这些行:

//select = br.next();    // old version with Scanner

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
  select = bufferedReader.readLine();
} catch (IOException e) {
  throw new RuntimeException(e);
}
System.out.println(">" + select + "<"); // should be able to see empty lines now...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top