I found a serious problem that can be replicated using the following code:
Scanner scanner = new Scanner(System.in);
System.out.println("First entry:");
System.out.println("->" + scanner.next());
System.out.println("Second entry:");
System.out.println("->" + scanner.nextLine());
If the user entry is "a", the call to nextLine()
will catch an empty String. I found out why this happen in other posts [1], [2]. The next()
call leaves just the '\n' caracter at the end of the line.
What I don't undestand is why the following code works:
System.out.println("First entry:");
System.out.println("->" + scanner.next());
System.out.println("Second entry:");
System.out.println("->" + new Scanner(System.in).nextLine());
Example:
For the input "a Hello World" the first block get the "a" in the next() call and the "Hello World" in the nextLine() call.
But in the second block of code the get the "a" in the next() call but "discard" the "Hello World" in the nextLine() call and waits for the user to promt again
*I know why in the first block of code the nextLine() call gets an empty String