为什么 input.nextint 方法有一个 作为剩余部分? [英] Why does input.nextint method have a as a leftover?
本文介绍了为什么 input.nextint 方法有一个
作为剩余部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这个问题的答案中,我不明白为什么 input.nextInt
有一个换行符作为剩余.
In the answer to this question I don't understand why the input.nextInt
has a newline character as a leftover.
扫描仪正在跳过 nextLine() 之后使用 next()、nextInt() 或其他 nextFoo()?
推荐答案
答案很简单:
Scanner#nextInt()
读取下一个整数,但不读取用户按下以提交整数的换行符 (ENTER
).
Scanner#nextInt()
reads the next integer but not the newline (ENTER
) the user presses to submit the integer.
要理解这一点,您必须知道您键入的所有内容都将写入缓冲区,Scanner
方法尝试从中读取.
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.
看下面的例子:
System.out.println("Enter a number: ");
int i = scanner.nextInt();
System.out.println("Enter a line: ");
String l = scanner.nextLine();
会发生什么:
- 用户看到
Enter a number:
并按下17
和ENTER
. - 扫描器将读取
17
但保留ENTER
的换行符. - 程序会写
Enter a line:
,但扫描器会读取ENTER
的换行符,而不是等待输入.
- The user sees
Enter a number:
and will press17
andENTER
. - The scanner will read the
17
but leave the newline of theENTER
. - The program will write
Enter a line:
but the scanner will read the newline of theENTER
instead of waiting for input.
这篇关于为什么 input.nextint 方法有一个 作为剩余部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文