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");
}
}
}
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