-1

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. :)

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73

2 Answers2

2

I think you might have got new lines in your text.txt file. Try changing the content of file to -

Gordon Freeman 27    
Adrian Shephard 22    
Barney Calhoun 19    
Alyx Vance 23

If you got a new line in between Gordon Freeman 27 and Adrian Shephard 23. This will throw the following error -

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
Sachin
  • 394
  • 1
  • 5
0

Your text file contains new lines. In this statement you are getting exception

 int age = Integer.parseInt(readSplit[2]);

Change your code to

   for (String read = readFromFile.readLine(); read != null; read = readFromFile.readLine()) {
            System.out.println(read+"a");
            if(!read.equals(""))//to check whether the line is empty
            {
            String[] readSplit = read.split("\\s+");
            int age = Integer.parseInt(readSplit[2]);
            System.out.println(readSplit[0] + " is " + age + " years old.");    
            }
        }
SatyaTNV
  • 4,137
  • 3
  • 15
  • 31