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

我的未来我决定 提交于 2019-11-27 04:16:54

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!