I keep getting this error in my code and I know it has something to do with the integer not being a number but I am unsure how to fix this. I'm sure this is very basic but so am I so I would appreciate any help possible. This has to be done in a do loop by the way. I know it would be better in a while.
Here are the bits of code which contain the information needed. Thank you.
String firstName, surname, id;
int luckynumber, lockernumber, grade, age;
char grade2;
try {
BufferedReader filein = new BufferedReader(new FileReader(new File(
"studentdetails.txt")));
do {
id = filein.readLine();
firstName = filein.readLine();
surname = filein.readLine();
age = Integer.parseInt(filein.readLine());
grade = Integer.parseInt(filein.readLine());
lockernumber = Integer.parseInt(filein.readLine());
age = 2010 - age;
} while (id != null);
filein.close();
} catch (FileNotFoundException fnfe) {
System.out.println(fnfe);
} catch (NumberFormatException nfe) {
System.out.print(nfe);
} catch (IOException e) {
System.out.print(e);
}
Edit - This is the file that is read in but with about 10 other people. Each word/number is on its own line in the file.
261
Patricia
Halangahu
1974
92
56
Assuming the file doesn't contain empty lines which could also trigger a NumberFormatException consider your case:
do {
id = filein.readLine();
//do more stuff
} while( id != null );
You're checking if you reached the end of the file by checking the id for being null. But if id
is null you're still completing the iteration and the parses will fail (you already reached the end of the file so what should age = Integer.parseInt(filein.readLine());
do then?).
So how do you solve that? One way would be to add a check right after reading the id:
do {
id = filein.readLine();
if( id == null) {
//end of stream, stop iteration
break;
}
//do more stuff
} while( true ); //you're breaking the loop from the inside already