19
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”后扫描仪仍会继续......我试过:

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

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

他们没有工作....程序继续并与初衷相悖,

4

8 回答 8

31

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

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

  • 输入“文件结束”标记。在(通常)为CTRL+的 UNIX 和 Mac OS 上D,以及在 Windows CTRL+上Z。这将导致hasNextLine()返回false

  • 输入一些被程序识别为意思是“我完成了”的特殊输入。例如,它可能是一个空行,也可能是一些特殊值,例如“exit”。该程序需要专门对此进行测试。

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


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

其他要考虑的事情是区分大小写(例如“exit”与“Exit”)以及前导或尾随空格的影响(例如“exit”与“exit”)。

于 2013-04-25T05:18:05.820 回答
4

字符串比较是使用.equals()and not完成的==

所以,试试scan.nextLine().equals("")

于 2013-04-25T05:17:39.530 回答
3

您将不得不寻找指示输入结束的特定模式,例如“##”

// 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();
    }
于 2013-04-25T05:21:46.007 回答
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。如果输入等于退出,则程序将退出。此外,用户可以按 control + c 退出程序。

于 2013-04-25T05:23:49.943 回答
1

您可以从控制台检查下一行输入,并检查您的终止条目(如果有)。

假设您的终止条目是“退出”,那么您应该尝试以下代码:-

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

试试这个代码。当您想关闭/终止扫描仪时,您应该输入终止行。

于 2013-04-25T05:48:28.113 回答
0

使用这种方法,您必须显式创建退出命令或退出条件。例如:

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

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

于 2013-04-25T05:17:10.730 回答
0

这就是我将如何做到的。说明了使用常量来限制数组大小和条目数,并且 double 除以 anintdouble产生double结果,因此您可以通过仔细声明来避免一些强制转换。同样将 an 分配int给声明的东西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);
    }
}
于 2020-02-17T17:03:54.387 回答
0

您可以通过检查长度是否为 来检查用户是否输入了空,此外,您可以通过在try-with-resources语句0中使用它来隐式关闭扫描仪:

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!
于 2020-11-25T01:17:13.383 回答