java - Scanner.nextInt() 正在移动到下一行,这怎么可能?

标签 java java.util.scanner

输入

  • 整数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() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) 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/

相关文章:

java - 有没有办法显式启用/禁用 Java 编译器对指令重新排序?

java - 我的时间介于开始时间和结束时间之间

java - Java 中的 Concat()

Java - 如何仅接受日期输入的整数?

java - 执行自定义 native 查询时无法提取 ResultSet

java - 从 1 到 20 查找 lcm,给出错误 "at Main.gcd(Main.java:21)"

java - Java中不区分大小写的replace()方法(使用indexOf)

java - 在遍历整个文件后,是否可以将扫描仪重置为文本的第一行?

java - 使用字符作为扫描仪的起点和终点

java - 为什么代码不读取 nextLine()?