当输入完成时如何终止Scanner?

23
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"之后继续运行,假设我要继续输入... 我尝试过:

只是想知道如何在输入完成后终止程序?由于扫描器会在多次“Enter”后继续运行,假设我要继续输入... 我尝试过:

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

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

他们没有工作... 程序继续运行并干扰了原本的意图。

8个回答

35
问题在于程序(比如你的程序)不知道用户何时完成输入,除非用户以某种方式告诉它。
用户可以通过以下两种方式之一来完成输入:
1. 输入“文件结束”标记。在UNIX和Mac OS上,通常是CTRL+D,在Windows上是CTRL+Z。这将导致hasNextLine()返回false。 2. 输入一些特殊的输入,被程序识别为“我完成了”。例如,它可以是一个空行,或者像“exit”这样的特殊值。程序需要专门测试这个。
(你还可以想象使用计时器,并“假设”用户已经完成,如果他们N秒或N分钟没有输入任何内容。但这不是一种用户友好的方式,在许多情况下也很危险。)
你当前的版本失败的原因是你使用==来测试空字符串。你应该使用equalsisEmpty方法。(参见如何在Java中比较字符串?)
其他需要考虑的事情包括大小写敏感性(例如"exit"与"Exit")以及前导或尾随空格的影响(例如" exit"与"exit")。

4
你需要寻找特定的模式,以指示输入结束,例如“##”。
// TODO Auto-generated method stub
    Scanner scan = new Scanner(System.in);
    try {
        while (scan.hasNextLine()){

            String line = scan.nextLine().toLowerCase();
            System.out.println(line);
            if (line.equals("##")) {
                System.exit(0);
                scan.close();
            }
        }

    } finally {
        if (scan != null)
        scan.close();
    }

4

字符串比较应使用.equals()而不是==

因此,请尝试scan.nextLine().equals("")


1
在这种情况下,我建议您使用do-while循环而不是while循环。
    Scanner sc = new Scanner(System.in);
    String input = "";
    do{
        input = sc.nextLine();
        System.out.println(input);
    } while(!input.equals("exit"));
sc.close();

为了退出程序,您只需要分配一个字符串标头,例如exit。如果输入等于exit,则程序将退出。此外,用户可以按control+c键退出程序。

1
你可以从控制台检查下一行输入,并检查是否有终止输入(如果有的话)。
假设您的终止输入是“quit”,那么您应该尝试使用以下代码:
Scanner scanner = new Scanner(System.in);
    try {
        while (scanner.hasNextLine()){

            // do  your task here
            if (scanner.nextLine().equals("quit")) {
                scanner.close();
            }
        }

    }catch(Exception e){
       System.out.println("Error ::"+e.getMessage());
       e.printStackTrace();
 }finally {
        if (scanner!= null)
        scanner.close();
    }

尝试这段代码。当您想关闭/终止扫描器时,应由您输入终止行。


0

使用这种方法,您必须明确创建一个退出命令或退出条件。例如:

String str = "";
while(scan.hasNextLine() && !((str = scan.nextLine()).equals("exit")) {
    //Handle string
}

此外,你必须使用 .equals() 而不是 == 来处理字符串相等的情况。 == 比较两个字符串的地址,除非它们实际上是同一个对象,否则永远不会为真。

0
您可以通过检查输入长度是否为0来确定用户是否输入了空值,此外,您还可以在try-with-resources语句中隐式地关闭扫描器:
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        System.out.println("Enter input:");
        String line = "";
        try (Scanner scan = new Scanner(System.in)) {
            while (scan.hasNextLine()
                    && (line = scan.nextLine().toLowerCase()).length() != 0) {
                System.out.println(line);
            }
        }
        System.out.println("Goodbye!");
    }
}

示例用法:

Enter input: 
A
a
B
b
C
c

Goodbye!

0
这是我会怎么做的。使用常量来限制数组大小和输入计数,以及将双精度除以整数得到的结果是双精度,因此您可以通过仔细声明事物来避免一些强制转换。还将一个int赋值给声明为double的变量也意味着您想将其存储为double,因此也不需要进行强制转换。
import java.util.Scanner;

public class TemperatureStats {

    final static int MAX_DAYS = 31;

    public static void main(String[] args){

        int[] dayTemps = new int[MAX_DAYS];
        double cumulativeTemp = 0.0;
        int minTemp = 1000, maxTemp = -1000;  

        Scanner input = new Scanner(System.in);

        System.out.println("Enter temperatures for up to one month of days (end with CTRL/D:");        
        int entryCount = 0;
        while (input.hasNextInt() && entryCount < MAX_DAYS)
            dayTemps[entryCount++] = input.nextInt();

        /* Find min, max, cumulative total */
        for (int i = 0; i < entryCount; i++) {
            int temp = dayTemps[i];
            if (temp < minTemp)
                minTemp = temp;
            if (temp > maxTemp)
                maxTemp = temp;
            cumulativeTemp += temp;
        }

        System.out.println("Hi temp.   = " + maxTemp);
        System.out.println("Low temp.  = " + minTemp);
        System.out.println("Difference = " + (maxTemp - minTemp));
        System.out.println("Avg temp.  = " + cumulativeTemp / entryCount);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接