Why does input.nextint method have a \n as a leftover?

こ雲淡風輕ζ 提交于 2021-02-05 06:43:05

问题


In the answer to this question I don't understand why the input.nextInt has a newline character as a leftover.

Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()?


回答1:


The answer is quite simple:

Scanner#nextInt() reads the next integer but not the newline (ENTER) the user presses to submit the integer.

To understand this you must know that everything you type will be written to a buffer, from which the Scanner methods try to read from.


Regard the following example:

System.out.println("Enter a number: ");
int i = scanner.nextInt();
System.out.println("Enter a line: ");
String l = scanner.nextLine();

What will happen:

  • The user sees Enter a number: and will press 17 and ENTER.
  • The scanner will read the 17 but leave the newline of the ENTER.
  • The program will write Enter a line: but the scanner will read the newline of the ENTER instead of waiting for input.



回答2:


This is purly a design decision, the reason nextInt() doesn't consume the newline character, is because there may be some other tokens that haven't been parsed yet, it would be most inappropriate to assume there's nothing left in the string, and consume the newline char.

For instance, you are given the following input
123 123 \n

Calling nextInt() will result in the following string left in the buffer
123 \n

Calling nextInt()again,
\n



来源:https://stackoverflow.com/questions/45979007/why-does-input-nextint-method-have-a-n-as-a-leftover

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