Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.Scanner does not return to Prompt

import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            System.out.println(s.next());
        }
        s.close();
    }
}

This program does not return to prompt (I have been running it through the Terminal). Why is that? How can I correct it?

like image 628
prometheuspk Avatar asked Jan 16 '26 22:01

prometheuspk


2 Answers

This program does not return to prompt (I have been running it through the Terminal). Why is that?

Because s.hasNext() will block until further input is available and will only return false if it encounters end of stream.

From the docs:

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan.

On a unix system you can end the stream by typing Ctrl+D which correctly returns control to the prompt, (or terminate the whole program by typing Ctrl+C).

How can I correct it?

You can either

  • reserve some input string used for terminating the program, as suggested by JJ, or
  • you could rely on the user closing the input stream with Ctrl+D, or you could
  • enclose the loop in a try/catch and let another thread interrupt the main thread which then exits gracefully.
  • do System.in.close() programatically from another thread.
like image 152
aioobe Avatar answered Jan 19 '26 13:01

aioobe


This is a reply to a comment above. Here, the application will quit when receiving "quit".

import java.util.Scanner;

class newClass {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            String temp = s.next();
            if(temp.trim().equals("quit"))
                System.exit(0);
            System.out.println(s.next());
        }
        s.close();
    }
}
like image 40
Marius Solbakken Mellum Avatar answered Jan 19 '26 15:01

Marius Solbakken Mellum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!