Mandile Schrosner Mandile Schrosner - 1 year ago 105
Java Question

Try-Catch While loop getting stuck on No Such Element Exception

public static ArrayList<Student> readStudentRecords(String fileName) throws FileNotFoundException {
Scanner input = new Scanner(new FileInputStream(fileName));
ArrayList<Student> students = new ArrayList<Student>();
String firstName, lastName, id, email, hashPW;
int maxCredits = 0;
while (input.hasNextLine()) {
try {
firstName =;
lastName =;
id =;
email =;
hashPW =;
maxCredits = input.nextInt();
Student student = new Student(firstName, lastName, id, email, hashPW, maxCredits);
} catch (IllegalArgumentException e) {
System.out.println("Illegal Argument Exception");;
} catch (NoSuchElementException e) {
System.out.println("No Such Element Exception");;
return students;

I am creating a program that reads a text file that lists a students first name, last name, id, email, hashed password, and max credits. Each line of the text file has a full suite of each element seperated by commas. I want the program to read the file, create a student object from each line (I have created and tested the Student class, including all getters and setters), and arrange the student objects in an array list. The program is getting looped at NoSuchElementException, and is only reading the first line of the text file, and ignoring the next 9. I'm not sure what exact format my try-catch statement should be in to ensure that it will not infinitely loop.

Answer Source

The first line in your try block reads the available line and then throws it away:

while (input.hasNextLine()) {
    try {

The reason you are getting the exception is that you throw away the line you just checked is there and then continue trying to read from input, whether or not there is anything after the line you just trashed.

You should do one of these:

  1. Capture that line and parse it (rather than calling or input.nextInt() in the following lines); or
  2. Eliminate the call to input.nextLine() and hope that each line properly conforms to the layout you expect; or
  3. Replace your entire while loop with calls to a csv parsing utility (as @Scary Wombat suggests in a comment).
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download