有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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“*”,但之后我得到了这个错误:

**********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不能


共 (2) 个答案

  1. # 1 楼答案

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

    while (s.hasNextLine()) {
      if(s.hasNextInt()){
        int i = s.nextInt();
        if ( i == 9);
        {
          System.out.print("*");
        }
      }
    } 
    
  2. # 2 楼答案

    • 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

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