2017-02-15 33 views
0
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 “*”,但后来我得到这个错误:为什么我会在hasNextLine上发生错误,但不会在hasNext上发生错误?

**********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) 

但是,如果使用的不是hasNextLine hasNext,它工作正常。

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

+0

什么是变量's'? –

+0

s是扫描文件的扫描仪 – Secret

回答

0

你应该设法得到它之前检查nextInt:

while (s.hasNextLine()) { 
    if(s.hasNextInt()){ 
    int i = s.nextInt(); 
    if (i == 9); 
    { 
     System.out.print("*"); 
    } 
    } 
} 
1
  • hasNextLine() 检查,看看是否有另一个linePattern在缓冲区中。
  • hasNext() 检查缓冲区中是否存在可解析的令牌,如 由扫描程序的分隔符分隔。

由于扫描仪的分隔符是空白,而linePattern是 也是白色的空间,有可能出现是在 缓冲区linePattern但没有解析的令牌。

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

所以这样你试图读取一个字符是不是有你的文件可能有一个空的换行符。

相关问题