java.util.Scanner jumps over input requests

大兔子大兔子 提交于 2019-12-01 08:10:53

问题


I am trying to receive input using java.util.Scanner:

Scanner scanner = new Scanner(System.in);
int bla = scanner.nextInt();
String blubb = scanner.nextLine();

But the nextLine() command just gets skipped and an empty string is returned. How can I solve this problem?


回答1:


The nextInt method does not consume the new line character after the integer so when you call nextLine it just reads the new line character immediately following the integer.

Example

If you have this input:

42\n
foo\n

The readInt call consumes the 42 but not the new line character:

\n
foo\n

Now when you call readLine it consumes the rest of the first line, which contains only the new line character.

Solution

Try discarding the rest of the line after the integer:

int bla = scanner.nextInt();
scanner.nextLine(); // Discard the rest of the line.
String blubb = scanner.nextLine();

Or use nextLine consistently to read each line and then parsing the string to an integer yourself:

String blaString = scanner.nextLine();
int bla = Integer.valueOf(blaString);
String blubb = scanner.nextLine();



回答2:


It isn't skipped:

int bla = scanner.nextInt(); 

Doesn't consume a new line, so your scanner is still on the first line when you hit Enter after you input your int. Then the scanner sees that it needs to consume the current line (The one where you inputted the int) and puts that remainder in blubb.




回答3:


I have had similar issues when my scanner was static. I made a new scanner that was local and it didn't skip over input requests.



来源:https://stackoverflow.com/questions/13993987/java-util-scanner-jumps-over-input-requests

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