Mandile Schrosner Mandile Schrosner - 3 months ago 27
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>();
input.useDelimiter(",");
String firstName, lastName, id, email, hashPW;
int maxCredits = 0;
while (input.hasNextLine()) {
try {
input.nextLine();
firstName = input.next();
lastName = input.next();
id = input.next();
email = input.next();
hashPW = input.next();
maxCredits = input.nextInt();
Student student = new Student(firstName, lastName, id, email, hashPW, maxCredits);
students.add(student);
} catch (IllegalArgumentException e) {
System.out.println("Illegal Argument Exception");
input.next();
} catch (NoSuchElementException e) {
System.out.println("No Such Element Exception");
input.next();
}
}
input.close();
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

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

while (input.hasNextLine()) {
    try {
        input.nextLine();
        ...

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 input.next() 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).