0

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

Community
  • 1
  • 1
Rafael Teles
  • 2,288
  • 2
  • 10
  • 31

2 Answers2

0

When you use Scanner.next(), you need to be careful about pressing "enter"/"carriage return" keys. As soon as you do that, scanner will read the input as carriage returned empty line.

If you run your first code sample with inputs

"a" helloWorld

, it should still work.

With your second sample, as you are creating a new Scanner, so it will read the input even if you have pressed enter key

Juned Ahsan
  • 63,914
  • 9
  • 87
  • 123
0

new Scanner(System.in) will create a new object and that parse from beginning.

check the below code .

    Scanner scanner = new Scanner(System.in);
    System.out.println("First entry:");
    System.out.println("->" + scanner.nextLine());
    System.out.println("Second entry:");
    System.out.println("->" + scanner.nextLine());

that works in both cases.

Ajmal Muhammad
  • 675
  • 5
  • 23