关于java:为什么我在hasNextLine上出错,而在hasNext上却没有?

Why do I get an error on hasNextLine, but not on hasNext?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for(int i = 0 ; i < 10 ; i++)
{
out.println(9);
}

out.close();

while (s.hasNextLine()) {
  int i = s.nextInt();
  if ( i == 9);
  {
  System.out.print("*");
  }
}

s.close();

它仍打印出10"*",但之后我收到此错误:

1
2
3
4
5
6
7
8
9
10
11
**********java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at insertionSort.main(insertionSort.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

但是如果我使用hasNext而不是hasNextLine,它可以正常工作。

所以我想知道为什么hasNext工作,但hasNextLine没有。


  • hasNextLine()
    checks to see if there is another linePattern in the buffer.
  • hasNext()
    checks to see if there is a parseable token in the buffer, as
    separated by the scanner's delimiter.

Since the scanner's delimiter is whitespace, and the linePattern is
also white space, it is possible for there to be a linePattern in the
buffer but no parseable tokens.

资料来源:https://stackoverflow.com/a/31993534/5333805

所以你的文件可能有一个空的换行符,所以你试着读一个不存在的字符。


在尝试获取之前,您应该检查nextInt:

1
2
3
4
5
6
7
8
9
while (s.hasNextLine()) {
  if(s.hasNextInt()){
    int i = s.nextInt();
    if ( i == 9);
    {
      System.out.print("*");
    }
  }
}