-
NoSuchElementException
Hey everyone!
I'm working on a small program that reads data from a file and puts it in a hashmap.
The file from which I'm reading looks like this:
something>anotherword
otherword>againword
...
Basically the first word before the > delimiter is the key and the other ones are values.
I've searched the web and find some solutions but not one that works for me.
This is the error part eclipse gave me:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1364)
at domainmodel.Woordenboek.leesIn(Woordenboek.java:25 )
at domainmodel.Woordenboek.<init>(Woordenboek.java:11 )
at ui.WoordenboekUI.main(WoordenboekUI.java:14)
This is the code that is supposed to scan the data into a hashmap:
Code:
public void leesIn() {
File dictfile = new File("NedEng.txt");
try {
Scanner scanfile = new Scanner(dictfile);
while (scanfile.hasNextLine()) {
Scanner scannerLijn = new Scanner(scanfile.nextLine());
scannerLijn.useDelimiter(">");
String desleutel = scannerLijn.next();
String dewaarde = scannerLijn.next();
woordenlijst.put(desleutel, dewaarde);
}
scanfile.close();
} catch (FileNotFoundException fnfe) {
// TODO Exception effectief gooien ! //
}
}
-
Use BufferedReader, its readLine method, and String's split method and simply check the length after split to ensure that you actually 2 (and only 2) elements. It is guaranteed to be, at least, more effecient.
-
We aren't allowed to use something else of code. But I found the problem using a counter inside the while loop. And the problem was that on line 127 there was this:
aanhanger van een rechtse partiright-hander>
with an empty space behind the delimiter. Stupid little problem!
-
More power to you, even though, persoanlly, I am quite sure your instructor did not say "USE SCANNER AND NOTHING ELSE", (s)he probably simply suggested that Scanner as one posiibility (not the most effecient by a long way, though), and that you simply did not want to change, but okay.