[Solved] I keep getting java.lang.ArrayIndexOutOfBoundsException: 5! How do I fix this? [closed]


Based on what you’ve shown:

testNum is greater than scores.length. This means that when you traverse the array by comparing your iterator (i) to testNum rather than its actual length, you will hit indexes which don’t exist.

For example, let’s say testNum = 8 and scores.length = 5. Then in your code, you will get an ArrayIndexOutOfBoundsException:5 because your loop goes through indexes 0, 1, 2, 3, and 4 (remember that arrays begin at index 0) then tries to access 5, which is out of bounds (as the Exception says).

You can properly traverse an array using either of the following techniques, depending on your use case:

for(int i = 0; i < scores.length; i++) {
    //do stuff
}

… or …

for(int score : scores) {
    //do stuff
}

solved I keep getting java.lang.ArrayIndexOutOfBoundsException: 5! How do I fix this? [closed]