【问题标题】:How to terminate Scanner when input is complete?输入完成后如何终止扫描仪?
【发布时间】:2020-08-26 11:59:46
【问题描述】:
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);  

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

【问题讨论】:

    标签: java


    【解决方案1】:

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

    用户可以通过两种方式做到这一点:

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

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

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


    您当前版本失败的原因是您使用== 来测试空字符串。您应该使用equalsisEmpty 方法。 (见How do I compare strings in Java?

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

    【讨论】:

      【解决方案2】:

      字符串比较是使用.equals() 而不是== 完成的。

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

      【讨论】:

        【解决方案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();
            }
        

        【讨论】:

          【解决方案4】:

          在这种情况下,我建议你使用 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();
          

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

          【讨论】:

            【解决方案5】:

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

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

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

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

            【讨论】:

              【解决方案6】:

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

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

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

              【讨论】:

                【解决方案7】:

                我会这样做。说明使用常量来限制数组大小和条目数,双精度除以 intdouble 产生 double 结果,因此您可以通过仔细声明来避免一些强制转换。同样将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);
                    }
                }
                

                【讨论】:

                  【解决方案8】:

                  你可以通过检查长度是否为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!
                  

                  【讨论】:

                    猜你喜欢
                    • 2017-09-23
                    • 1970-01-01
                    • 2016-06-20
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2017-09-04
                    • 1970-01-01
                    相关资源
                    最近更新 更多