How to test for blank line with Java Scanner?

Jiew Meng picture Jiew Meng · Sep 6, 2011 · Viewed 90.4k times · Source

I am expecting input with the scanner until there is nothing (i.e. when user enters a blank line). How do I achieve this?

I tried:

while (scanner.hasNext()) {
    // process input
}

But that will get me stuck in the loop

Answer

Bart Kiers picture Bart Kiers · Sep 6, 2011

Here's a way:

Scanner keyboard = new Scanner(System.in);
String line = null;
while(!(line = keyboard.nextLine()).isEmpty()) {
  String[] values = line.split("\\s+");
  System.out.print("entered: " + Arrays.toString(values) + "\n");
}
System.out.print("Bye!");