0

I'm reading from standard input using the following loop:

Scanner stdin = new Scanner(System.in);

while (stdin.hasNextLine() && stdin.nextLine() != null) {

        String line = stdin.nextLine();

        if (!(line.contains("#"))) {
            input.add(line);
        }

        if (line.contentEquals("q")) {
            break;
        }

 }

Now this is easy to terminate if I simply type q and press enter, however I'm supposed to terminate the program when the user presses Ctrl + d on a new line. I can't get this to work, when I press Ctrl + d nothing happens.

MatWdo
  • 1,610
  • 1
  • 13
  • 26
Alk
  • 5,215
  • 8
  • 47
  • 116

1 Answers1

0

The problem is that hasNextLine() and hasLine() wait for the user to input "enter".

Ctrl-D is not ... enter.

So you have to look into means that go "character by character" for example.

Maybe scanner.next() will return something more useful instead.

Beyond that, things are even more complicated, see here for example.

Thus, the real, not so helpful answer is actually: Java scanner and "ctrl-something" keystrokes are not exactly best friends.

You could probably look into some libraries providing curses like functionality instead.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • If I change the while condition to `while(stdin.next() != null)` I get a `NoSuchElementException` exception on `Ctrl + d` – Alk Feb 07 '17 at 15:32
  • Is there something else you suggest I can use to read from standard input instead of the scanner? – Alk Feb 07 '17 at 15:33
  • So should i basically try to catch that exception and assume that when it happens all the input has been supplied? – Alk Feb 07 '17 at 15:34
  • That would be one option. The other option would be to change from "scanner" to something more "curses" like ... see my updates again! – GhostCat Feb 07 '17 at 15:35
  • I will accept it, gotta wait 6 minutes though – Alk Feb 07 '17 at 15:36