4

How do you keep the console from closing after the program is done in Java?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
mikigal
  • 61
  • 1
  • 1
  • 3

4 Answers4

4

readLine() waits until you press a key:

public static void main (String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    in.readLine();
}
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
3

The simplest way I've found:

Scanner scanner = new Scanner(System.in); 
scanner.nextLine();
Ruben
  • 331
  • 5
  • 13
1

There are several ways to achieve this.

  • You can request the user for input at the end of your main method.

  • You can create and start a thread. Deamon threads are automatically closed when your main method finishes. However non-deamon threads will keep your application alive until they are finished.

  • Or just call wait on an object.

I'm not sure though, why you would want to keep an application alive, if it's not doing anything anymore.

Using a non-deamon thread:

// example of an application that never closes.
public static void main(String[] args) {
    new Thread(new Runnable() {
        @Override
        public synchronized void run() {
            for(;;)
                try {
                    wait();
                } catch (InterruptedException e) {
                }
        }
    }).run();
}

Calling wait on an object:

public static void main(String[] args)throws Exception {
    Object o = new Object();
    synchronized (o) {
        o.wait();
    }
}
bvdb
  • 22,839
  • 10
  • 110
  • 123
-1

Firing empty Scanner input at the end of the code works each time, because the scanner waits for user to press ENTER.

//to-do your code
Scanner.nextLine();

Shame Java does not have inbuilt wait or pause command for the console apps.

EDIT: If you want to construct Scanner, you do it like this:

Scanner scanner = new Scanner(System.in); 
scanner.nextLine();

System.in is parameter that tells the scanner which input stream to use.

The Law
  • 344
  • 3
  • 20
  • What String put in Scanner constructor? – mikigal Oct 30 '15 at 16:48
  • I have code: Scanner pause = new Scanner(""); pause.nextLine(); But I have crash Exception in thread "main" java.util.NoSuchElementException: No line found – mikigal Oct 30 '15 at 16:51