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

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

问题描述

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();
        }
    }

我想知道如何在我拥有程序后终止程序完成输入输入?
由于扫描仪在几次输入之后仍然会继续,假设我要继续输入输入...
我试过:

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上(通常) CTRL + D ,在Windows上 CTRL + Z 。这将导致 hasNextLine()返回 false

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

输入一些程序识别为我已完成的特殊输入。例如,它可能是一个空行,或某些特殊值,如退出。该程序需要专门测试。

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分钟内没有输入任何输入,则用户已完成。但这不是一种用户友好的方式。)

您当前版本失败的原因是您使用 == 来测试空字符串。您应该使用等于 isEmpty 方法。 (请参阅如何比较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天全站免登陆