I am a beginner at Java (and programming in general). I am inputting information from a text file that contains the following text:
Gordon Freeman 27
Adrian Shephard 22
Barney Calhoun 19
Alyx Vance 23
I got an ArrayIndexOutOfBoundsException in this method:
private static void readFile2() {
System.out.println("\nReading from file 2:\n");
File file = new File("C:/Users/Reflex FN/Documents/IOTest2/text.txt");
try {
BufferedReader readFromFile = new BufferedReader(
new FileReader(file));
String read = readFromFile.readLine();
while(read != null) {
String[] readSplit = read.split(" ");
int age = Integer.parseInt(readSplit[2]);
System.out.println(readSplit[0] + " is " + age + " years old.");
read = readFromFile.readLine();
}
readFromFile.close();
} catch (FileNotFoundException ex) {
System.out.println("File not found: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("IO Exception: " + ex.getMessage());
}
}
It worked for the first time; it printed:
Gordon Freeman is 27 years old.
However, before anything else was printed, the ArrayIndexOutOfBoundsException was thrown. What did I do wrong, exactly? The source of the exception seems to be this line:
int age = Integer.parseInt(readSplit[2]);
By the way, I am new here, so I hope I did not misplace this question.
Thank you. :)