问题
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