¿Cómo terminar el escáner cuando se completa la entrada?

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

y

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

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

preguntado el 25 de abril de 13 a las 06:04

8 Respuestas

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:

  • Enter an "end of file" marker. On UNIX and Mac OS that is (typically) CTRL+Dy en Windows CTRL+Z. That will result in hasNextLine() volver 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.

(You could also conceivably use a timer, and asumir 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.)


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 ¿Cómo comparo cadenas en 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").

Respondido el 24 de enero de 21 a las 02:01

String comparison is done using .equals() y no ==.

Entonces, prueba scan.nextLine().equals("").

Respondido 25 Abr '13, 06:04

You will have to look for specific pattern which indicates end of your input say for example "##"

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

Respondido 25 Abr '13, 06:04

In this case, I recommend you to use do, while loop instead of while.

    Scanner sc = new Scanner(System.in);
    String input = "";
    do{
        input = sc.nextLine();
        System.out.println(input);
    } while(!input.equals("exit"));
sc.close();

In order to exit program, you simply need to assign a string header e.g. exit. If input is equals to exit then program is going to exit. Furthermore, users can press control + c to exit program.

Respondido 25 Abr '13, 06:04

You can check the next line of input from console, and checks for your terminate entry(if any).

Suppose your terminate entry is "quit" then you should try this code :-

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

Try this code.Your terminate line should be entered by you, when you want to close/terminate the scanner.

Respondido 25 Abr '13, 06:04

With this approach, you have to explicitly create an exit command or an exit condition. For instance:

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

Additionally, you must handle string equals cases with .equals() no ==. == compares the addresses of two strings, which, unless they're actually the same object, will never be true.

Respondido 25 Abr '13, 06:04

Here's how I would do it. Illustrates using a constant to limit array size and entry count, and a double divided by an int es un double produce un double result so you can avoid some casting by declaring things carefully. Also assigning an int to something declared double also implies you want to store it as a double so no need to cast that either.

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

Respondido 17 Feb 20, 17:02

You can check if the user entered an empty by checking if the length is 0, additionally you can close the scanner implicitly by using it in a probar con recursos declaración:

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!");
    }
}

Ejemplo de uso:

Enter input: 
A
a
B
b
C
c

Goodbye!

respondido 25 nov., 20:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.