Scanner.nextInt()正在移至下一行,这怎么可能?

时间:2019-07-01 14:02:26

标签: 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()如何进入下一行?除.nextFoo()以外的所有.next().nextLine()都只读取直到有一个空格并将光标指针保持在那里,对吗?那怎么去换行符?

1 个答案:

答案 0 :(得分:1)

通过Scanner Javadoc:

  

next()hasNext()方法及其原始类型的伴随方法(例如nextInt()hasNextInt())首先跳过任何与定界符模式匹配的输入,然后尝试返回下一个令牌。

因此,光标位于换行符之前,然后当您调用nextInt()时,在使用该数字之前跳过换行符和其他任何空格。

您的包含nextLine()的代码将起作用,只要您的输入文件以换行符结尾。通常以换行符结束文本文件-许多编辑器会强迫您使用一个换行符,或者如果缺少该文件则显示警告。