1

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.

Ivaylo Toskov
  • 3,911
  • 3
  • 32
  • 48
  • 2
    http://stackoverflow.com/questions/16206813/how-to-terminate-scanner-when-input-is-complete – Roman Pustylnikov Oct 25 '15 at 21:29
  • http://stackoverflow.com/questions/5488072/reading-in-from-system-in-java – Oleg Sklyar Oct 25 '15 at 21:30
  • I believe that the given duplicate is not a duplicate. OP says that program works in Ubuntu but doesn't in Debian. And that it only starts running `myFunction` after EOF is entered, which is clearly not an issue of not knowing that EOF should be entered at all. – RealSkeptic Oct 25 '15 at 21:34
  • OP: please show how you run your program in the two environments, what JVM is installed on them, what terminal emulator you're using etc. – RealSkeptic Oct 25 '15 at 21:36
  • @RealSkeptic exactly, both suggested questions do not really give an answer to my question. After I type `EOF` the program works as intended, but the loop does not get entered before I do (it does not get entered when I force a new line). I updated the details with the requested information. – Ivaylo Toskov Oct 25 '15 at 21:46
  • Are you running the program the same way? running `java -jar something`? Same classpath? Or using a shell script or some pipe? – RealSkeptic Oct 25 '15 at 21:54
  • Yes, I run it the same way using `ant` that generates a `jar` and specifying some arguments. The `classpath` is specified by the same `build.xml` and is therefore the same. I type in the lines manually. – Ivaylo Toskov Oct 25 '15 at 21:56

1 Answers1

1

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
Achintha Gunasekara
  • 1,165
  • 1
  • 15
  • 29