Ivaylo Toskov
Ivaylo Toskov

Reputation: 4031

Java's Scanner would read only after typing EOF

I have the following code:

Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
    String commandArgs[] = sc.nextLine().split("\\s+");
    myFunction(commandArgs[]);
    // Do something with commandArgs

The problem is that right after I type a line, nothing really happens. I can type multiple lines without result, but after I type EOF (Ctrl+D) they get read all at once and it causes multiple calls of myFunction.

This happens when executed on a Debian distribution with xterm emulator and the following java version:

java version "1.7.0_03"
OpenJDK Runtime Environment (IcedTea7 2.1.7) (7u3-2.1.7-1)
OpenJDK 64-Bit Server VM (build 22.0-b10, mixed mode)

The program works as intended on Ubuntu 14.04 with gnome-terminal-server and Java 8 installed.

Upvotes: 1

Views: 97

Answers (1)

Achintha Gunasekara
Achintha Gunasekara

Reputation: 1165

Well, instead trying,

sc.hasNext()

could you try

sc.hasNextLine()

This seems to have resolved this issue on Debian for me,

Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()) {
    String commandArgs[] = sc.nextLine().split("\\s+");
    myFunction(commandArgs[]);
    // Do something with commandArgs

Upvotes: 1

Related Questions