Struggling to figure out solution to fix IndexOutOfBoundsException

I am working on a project where you have to shoot an enemy. Unfortunetly when the bullet hits the enemy if only one shot is currently active it will throw IndexOutOfBoundsException. I am lost on what to do the remedy this so your help is appriciated.

if(bullets.size() > 0) {
    for(int i = 0; i < bullets.size(); i++) {
         if(shootingEnemys.size() > 0) {
             for(int j = 0; j < shootingEnemys.size(); j++) {
                 if((bullets.get(i).x >= shootingEnemys.get(j).x - 25) && (bullets.get(i).x <= shootingEnemys.get(j).x + 25) && (bullets.get(i).y >= shootingEnemys.get(j).y - 25) && (bullets.get(i).y <= shootingEnemys.get(j).y + 25)) {
                     shootingEnemys.remove(j);
                     bulletSprite = loadImage("Bullet_Hit.png");
                     bulletSprite.resize(20, 20);
                     score += 200;
                     bullets.remove(i);
                }
            }
        }
    }
}

thank you again for your help

1 Like

One reason could be that you use remove().
Better is to set a marker isDead = true; (which is a new variable in the class).

Then in two separate for loops (after the current loops), go backwards through the arrays using
for(int j... and say
if (shootingEnemys.get(j).isDead) shootingEnemys.remove(j);

(Processing doesn’t like remove() when going through an ArrayList forward)

Remark

Not sure why you do this here? It should be in setup(). Both commands are very processor costly.
(Just as a remark)

1 Like

First, when you remove items from an ArrayList in a loop you should loop it backwards. Otherwise, you skip items next to the removed ones. For example, if you delete an item with index 2, then the next shifts to its place and you jump over it to index 3.

Second, you don’t really need to check the length of the ArrayLists like that. If it’s 0 your loops will do it for you, since 0 < 0 is a false statement.

UPD. Got it. Looks like the error appears because you are deleting enemies and bullets in the same loop. It is possible that you deleted all the items from one of the lists but still trying to check them in that long condition. Using ‘isDead’ property as @Chrisir described will help.

2 Likes