为什么input.nextint方法有一个\ n剩余呢? [英] Why does input.nextint method have a \n as a leftover?
本文介绍了为什么input.nextint方法有一个\ n剩余呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在回答这个问题时,我不明白为什么input.nextInt
的剩余字符是换行符.
In the answer to this question I don't understand why the input.nextInt
has a newline character as a leftover.
扫描仪在使用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方法有一个\ n剩余呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文