This site requires JavaScript, please enable it in your browser!
Greenfoot back
Vellyxenya
Vellyxenya wrote ...

2015/10/28

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

Vellyxenya Vellyxenya

2015/10/28

#
Hi I'm trying the following code:
private void mvt2()
    {
        if(getWorld()!= null)
        {
            Boss8 boss = (Boss8) getWorld().getObjects(Boss8.class).get(0);
            if(Boss8.harvest == true)
            {
                counter++;
                if(counter == 1 || counter == 2)
                {
                    harvestRotation = this.getRotation()+90;
                    adjust();
                }
                //harvestRotation = this.getRotation()+90;
                if(this.getRotation() != harvestRotation)
                {
                    rotation2++;
                    adjust();
                    setRotation(this.getRotation()+rotation2);
                }
            }
        }
    }
But once I kill the boss... it tells me: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0... How can i fix that please?
danpost danpost

2015/10/28

#
Once there is no Boss8 object in the world, 'getObjects' in line 5 will return a List object that has no elements (size of zero). As such, you cannot get the first element which does not exist from that list (or, rather, you cannot execute 'get(0)' on an empty list). You can ask if the list is empty first, to avoid the error by replacing lines 5 and 6 with this:
if (! getWorld().getObjects(Boss8.class).isEmpty() && ((Boss8)getWorld().getObjects(Boss8.class).get(0)).harvest)
davmac davmac

2015/10/28

#
I guess that 'harvest' must be a static variable, for that code to compile. Is that intended? Given that it's static, do you really need a reference to the Boss8 instance at all? You could presently just remove the 5th line from the code you posted and you'd no longer get the error (though whether it would then do what you want, I'm not sure).
danpost danpost

2015/10/28

#
If the 'harvest' field is not supposed to be static, then your line 6 should be:
if (boss.harvest == true)
// or simply
if (boss.harvest)
To determine whether the field should be static or not, ask yourself "if there were two Boss8 objects in the world, would it be possible for the 'harvest' value for one be different than the value for the other?". If the answer is yes, then the field should not be static.
Vellyxenya Vellyxenya

2015/11/1

#
I see, thank you very much for your help! :)
You need to login to post a reply.