输入完成后如何终止扫描仪? [英] How to terminate Scanner when input is complete?

查看:33
本文介绍了输入完成后如何终止扫描仪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        try {
            while (scan.hasNextLine()){

                String line = scan.nextLine().toLowerCase();
                System.out.println(line);   
            }

        } finally {
            scan.close();
        }
    }

只是想知道在我完成输入后如何终止程序?由于假设我将继续输入输入,扫描仪在几次Enter"后仍会继续...我试过了:

Just wondering how I can terminate the program after I have completed entering the inputs? As the scanner would still continue after several "Enter" assuming I am going to continue entering inputs... I tried:

if (scan.nextLine() == null) System.exit(0);

if (scan.nextLine() == "") System.exit(0);  

他们没有工作......程序继续并且与最初的意图混乱,

They did not work.... The program continues and messes with the original intention,

推荐答案

问题是一个程序(比如你的)不知道用户已经完成输入,除非用户......不知何故......告诉它.

The problem is that a program (like yours) does not know that the user has completed entering inputs unless the user ... somehow ... tells it so.

用户可以通过两种方式执行此操作:

There are two ways that the user could do this:

  • 输入文件结尾"标记.在 UNIX 和 Mac OS 上(通常)CTRL+D,在 Windows 上 CTRL+Z.这将导致 hasNextLine() 返回 false.

  • Enter an "end of file" marker. On UNIX and Mac OS that is (typically) CTRL+D, and on Windows CTRL+Z. That will result in hasNextLine() returning false.

输入一些被程序识别为我完成了"的特殊输入.例如,它可以是一个空行,或者一些特殊的值,比如exit".程序需要专门为此进行测试.

Enter some special input that is recognized by the program as meaning "I'm done". For instance, it could be an empty line, or some special value like "exit". The program needs to test for this specifically.

(您也可以使用计时器,并且假设如果用户在 N 秒或 N 分钟内没有输入任何输入,则他们已经完成.但这不是用户友好的方式,而且在很多情况下会很危险.)

(You could also conceivably use a timer, and assume that the user has finished if they don't enter any input for N seconds, or N minutes. But that is not a user-friendly way, and in many cases it would be dangerous.)

您当前版本失败的原因是您使用 == 来测试空字符串.您应该使用 equalsisEmpty 方法.(请参阅如何比较 Java 中的字符串?)

The reason your current version is failing is that you are using == to test for an empty String. You should use either the equals or isEmpty methods. (See How do I compare strings in Java?)

其他需要考虑的事项是区分大小写(例如退出"与退出")以及前导或尾随空格的影响(例如退出"与退出").

Other things to consider are case sensitivity (e.g. "exit" versus "Exit") and the effects of leading or trailing whitespace (e.g. " exit" versus "exit").

这篇关于输入完成后如何终止扫描仪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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