Tyler Rossi :
I'm trying to create Student objects by reading from a given text file, but the text file has a bunch of empty blank lines under the actual info. I am not allowed to edit the text file in any way, and am also not allowed to use any other methods besides scanner for reading from the file. Everything works fine until I get to the bottom of the file, where a NoSuchElementException
is thrown and the code fails.
ArrayList<Student> Students = new ArrayList<>();
while (fileIn.hasNextLine()) {
Student student = new Student(fileIn.next(), fileIn.next(), fileIn.nextInt());
student.setExam1(fileIn.nextInt());
student.setExam2(fileIn.nextInt());
student.setExam3(fileIn.nextInt());
Students.add(student);
fileIn.nextLine();
System.out.println(student.toString());
}
The file looks like this
Peck CSI1000 12345 97 76 72
Rhodes CSI1000 87649 98 70 73
Rinke CSI1000 87649 78 70 78
Romanski CSI1000 87649 84 84 95
Rombach CSI1000 12345 82 86 96
Ruan CSI1000 87649 70 94 76
Ruc CSI1000 87649 97 98 80
Scott CSI1000 87649 90 80 73
Shah CSI1000 87649 98 72 71
Teal CSI1000 87649 89 72 99
Tingley CSI1000 87649 76 85 72
Towne CSI1000 87649 71 71 100
Tucker CSI1000 12345 89 71 93
Ureel CSI1000 87649 76 80 99
Wallace CSI1000 87649 76 100 71
Weber CSI1000 87649 75 73 75
Wierszewski CSI1000 12345 93 90 72
Wilmot CSI1000 12345 85 96 74
Wilson CSI1000 12345 91 75 97
Yang CSI1000 87649 83 80 85
Yasoni CSI1000 87649 78 90 76
JRowan :
you can try to catch the exception
ArrayList<Student> Students = new ArrayList<>();
while (fileIn.hasNextLine()) {
try{
Student student = new Student(fileIn.next(), fileIn.next(), fileIn.nextInt());
student.setExam1(fileIn.nextInt());
student.setExam2(fileIn.nextInt());
student.setExam3(fileIn.nextInt());
Students.add(student);
fileIn.nextLine();
System.out.println(student.toString());
}catch(NoSuchElementException e){
//break;
fileIn.nextLine();
System.out.println("exception");
}
}
or you can just break
inside the catch block if after the exception you aren't expecting any more information anyway
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=355528&siteId=1