本文介绍了为什么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 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.
更多推荐
为什么input.nextint方法有一个\ n剩余呢?
发布评论