Search code examples
androidonclicklogcatindexoutofboundsexception

Origin of ArrayIndexOutOfBoundsException in android?


I made a 5x5 2D array of square buttons, which was defined in a class called organisms, and arranged them them into a game board right to left, top to bottom. When an organism is clicked it changes color (and clicking it again restores its original color). When you click a (different, non organism) button on the side of the array, all of the buttons on the right of those organisms that were already clicked in the array should themselves change color. In the code, this onClick method is called IterateListener().

Here is the problem. I try to do the last part, where I click the button on the side, and the app stops and I get an ArrayIndexOutOfBounds.

E/AndroidRuntime(893): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=5; index=5

I make sure it is referring to an organism in the middle of the array, so the organism to the right should be within bounds. What else would be throwing an arrayIndexOutOfBounds? Let me know if there are any more parts of the code you want to see, but for now I am showing the parts of code that Logcat specifically complained about.

Here is the code for the getRightOrganism:

public Organism findRightOrg(Organism org) {
    return Col[org.getRow() + 1][org.getCol()];

}

Here is the code for the onClick:

public void IterateListener(View v) {
    for (int i = 0; i < colony.getWidth(); i++)
        for (int j = 0; j < colony.getHeight(); j++) {
            if (colony.getOrg(i, j).isAlive()) {
                colony.findRightOrg(colony.getOrg(i, j)).liveO();
                }
        }
}

Thanks so much!


Solution

  • Well, in an array you can iterate only through 0 to length-1. So in your i = colony.getWidth() - 1, you try to find an element with row = lenght-1+1 = length, which is out of bounds for that array.