0

So I have this code... and this is what a section of it looks like.

File File = new File("data2.txt");
    Scanner readUpdate = new Scanner(File);
    Player[] updatePlayers = new Player[200];
    String updateSTR;
    int updateTotalCounter = 0;
    while (readUpdate.hasNext()) {

        updateSTR = readUpdate.nextLine();
        String [] updateData = updateSTR.split(",");
        updatePlayers[updateTotalCounter] = new Player(updateData[0], updateData[1],updateData[2], 
                Integer.parseInt(updateData[3]), Integer.parseInt(updateData[4]));

        updateTotalCounter++;

    }

    readUpdate.close();

Java keeps coming up and telling me that

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at Main.main(Main.java:43)

I don't understand what this means. Any clues??

Jorge
  • 1,136
  • 9
  • 15
Megan
  • 1
  • 1

2 Answers2

2

That means that you're trying to access to a position in your array that is bigger than the number of elements in the array, so you get that common exception.

You're supposing that the array updateData has 5 positions for every line you read, and that seems to be false for at least one of the lines and so the exception is thrown.

Make sure that

String [] updateData = updateSTR.split(",");

Is size 5 (from 0 to 4) for all the lines. Fix the problem this way, but notice that some of the lines won't be processed:

File File = new File("data2.txt");
    Scanner readUpdate = new Scanner(File);
    Player[] updatePlayers = new Player[200];
    String updateSTR;
    int updateTotalCounter = 0;
    while (readUpdate.hasNext()) {

        updateSTR = readUpdate.nextLine();
        String [] updateData = updateSTR.split(",");
        if (updateData.lenght < 5) {
            // invalid line format... print any message...
        } else {
            updatePlayers[updateTotalCounter] = new Player(updateData[0], updateData[1],updateData[2], 
                Integer.parseInt(updateData[3]), Integer.parseInt(updateData[4]));

            updateTotalCounter++;
        }

    }

    readUpdate.close();
Jorge
  • 1,136
  • 9
  • 15
0

Better to check the length of array,

String [] updateData = updateSTR.split(",");
if(updateData.length > 4){
        updatePlayers[updateTotalCounter] = new Player(updateData[0], updateData[1],updateData[2], 
                Integer.parseInt(updateData[3]), Integer.parseInt(updateData[4]));
}
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55