DDrum DDrum - 3 months ago 9
Java Question

Java multiline text file import causes NoSuchElementException

I'm pretty new to coding, but thought I'd try some sort of random name picker and here is my code:

public class Randomnametest {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
randName();
}

private static void randName() {
try {
File names = new File("names.txt");
Scanner reader = new Scanner(names);
String line = reader.nextLine();
List<String> lines = new ArrayList<String>();
while (line != null) {
lines.add(line);
line = reader.nextLine();
}
Random r = new Random();
String randomLine = lines.get(r.nextInt(lines.size()));
System.out.println(randomLine);
reader.close();
} catch (FileNotFoundException ex) {
System.out.println("File was not found");
}
}

}


I thought I did everything right, but every time I run it, I get a NoSuchElementException and I have no idea what I did wrong. This is the only class I have in the project as it was just to test if I could make something like this on my own. The file "names.txt" is in the right directory as I can open the file and read the first line. Any help is welcome, also if I did something wrong with the naming conventions, please tell me as I'm still not a 100% sure about them.

Answer

This is almost correct, but your error comes from you trying to call reader.nextLine() without knowing whether there is more to read or not.

So once all lines have been read, when you call reader.nextLine(), it throws a NoSuchElementException.

The way to go is to have a while that calls reader.hasNext().

So it should go like this :

while( reader.hasNext() ){
  lines.add(reader.nextLine());
}

You don't need your line variable.

Another small note : to follow conventions your class should be called RandomNameTest instead of RandomnameTest