Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

java - Why does input.nextint method have a as a leftover?

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()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...