Can’t use Scanner.nextInt() and Scanner.nextLine() together [duplicate]

The problem is the '\n' character that follows your integer. When you call nextInt, the scanner reads the int, but it does not consume the '\n' character after it; nextLine does that. That is why you get an empty line instead of the string that you were expecting to get.

Let’s say your input has the following data:

12345
hello

Here is how the input buffer looks initially (^ represents the position at which the Scanner reads the next piece of data):

1  2  3  4  5 \n h  e  l  l  o \n
^

After nextInt, the buffer looks like this:

1  2  3  4  5 \n h  e  l  l  o \n
              ^

The first nextLine consumes the \n, leaving your buffer like this:

1  2  3  4  5 \n h  e  l  l  o \n
                 ^

Now the nextLine call will produce the expected result. Therefore, to fix your program, all you need is to add another call to nextLine after nextInt, and discard its result:

k = in.nextInt();
in.nextLine(); // Discard '\n'
input = in.nextLine();

Leave a Comment