输入
- 整数N
- 接下来有 N 行,每行有两个空格分隔的整数 p 和 q。
所以,我知道 nextLine()
读取整行并将光标移动到下一行,而 nextFoo()
仅读取直到遇到空格并且将光标保留在那里(不将其移动到新行)。
所以最初我尝试了这个:-
int N = Integer.parseInt(in.nextLine()); //reading the whole line and parsing it to Integer. The cursor pointer is moved to the next line
while(--N>=0){
p = in.nextInt(); q = in.nextInt(); //reading the two space seperated integers
in.nextLine();//to move the cursor to the next line
}
但这无法正常工作,无法读取我输入的最后一个 p 和 q。
更改为:
int N = in.nextInt();
while(--N>=0){
p = in.nextInt(); q = in.nextInt();
}
并且运行良好。 nextInt()
如何转到下一行?除 .nextLine()
之外的所有 .nextFoo()
和 .next()
仅读取直到出现空格并将光标指针保留在那里, 正确的?那么这将如何换行呢?
最佳答案
来自扫描器
Javadoc:
The
next()
andhasNext()
methods and their primitive-type companion methods (such asnextInt()
andhasNextInt()
) first skip any input that matches the delimiter pattern, and then attempt to return the next token.
因此,光标位于换行符之前,然后当您调用 nextInt()
时,会在消耗数字之前跳过换行符和任何其他空白。
只要您的输入文件以换行符结尾,包含 nextLine()
的代码就可以工作。通常以换行符结束文本文件 - 许多编辑器要么强制您使用换行符,要么在缺少换行符时显示警告。
关于java - Scanner.nextInt() 正在移动到下一行,这怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56837055/