java.util.NoSuchElementException on reading a file (Scanner) [duplicate]

依然范特西╮ 提交于 2019-12-11 23:42:05

问题


I have a text file with 3 words on it, and on trying to read these words I get the following error:

Exception in thread "main" java.util.NoSuchElementException  
    at java.util.Scanner.throwFor(Unknown Source)  
    at java.util.Scanner.next(Unknown Source)  
    at search.search(search.java:121)  
    at main.main(main.java:38)  

Below is the code in question:

Scanner reader = new Scanner(path + client + "\\" + cat +"\\" + query + ".arch");  
while (reader.hasNext()){  
    String a = reader.next();  // line 121
    String b = reader.next();  
    String c = reader.next();  
    file = new File (path + client + "\\" + a +"\\" + b + ".arch");  
    print(file);  
}

Below are the contents of the file:

po ref refc (with a new line at the end)

What gives? I've used a very similar system before, with the same file, and everything worked, I even use a very similar system some lines below.
Btw the String c is not yet implemented but shall be further down.


回答1:


Are you sure line 121 is not one of the next lines?

You check reader.hasNext() to make sure there is another entry, but you then read 3 entries in a, b, c. If there is only one for example, b = reader.next() would fail.



来源:https://stackoverflow.com/questions/11602492/java-util-nosuchelementexception-on-reading-a-file-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!