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

and

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

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

Jørgen R
  • 10,568
  • 7
  • 42
  • 59
user2318175
  • 223
  • 1
  • 2
  • 5

8 Answers8

35

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+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.

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

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
4

String comparison is done using .equals() and not ==.

So, try scan.nextLine().equals("").

Shobit
  • 776
  • 1
  • 6
  • 20
4

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();
    }
nchouhan
  • 101
  • 1
  • 1
1

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.

Jason
  • 1,298
  • 1
  • 16
  • 27
1

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.

JDGuide
  • 6,239
  • 12
  • 46
  • 64
0

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() not ==. == compares the addresses of two strings, which, unless they're actually the same object, will never be true.

0

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 is a double produces a 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);
    }
}
clearlight
  • 12,255
  • 11
  • 57
  • 75
0

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 try-with-resources statement:

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

Example Usage:

Enter input: 
A
a
B
b
C
c

Goodbye!
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40