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

2012/11/16

IndexOutOfBounds - Please help!

benessto benessto

2012/11/16

#
Hi, I try to switch to another world using an ArrayList This section of the code can be compiled but when my "Rocket" is colliding my "Exit", then the error pops up. java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 at java.util.ArrayList.rangeCheck(ArrayList.java:604) at java.util.ArrayList.get(ArrayList.java:382) at Exit.changeLevel(Exit.java:43) at Exit.act(Exit.java:32) This is the code of the method "changeLevel" in the class "Exit" which errored:
    
    private void changeLevel(Rocket tempRocket)
    {
        for (int i = 0; i <= WorldManager.level.size(); ++i)
        {
            if (WorldManager.isOfClass(WorldManager.level.get(i), getWorld().getClass()))
            {
                nextLevel = WorldManager.level.get(i+1);
            }
        }
        getWorld().removeObject(tempRocket);
        Greenfoot.setWorld(nextLevel);
PS: -"WorldManager" is a subclass of World. It's function is to manage all the worlds. In the "WorldManager" is the ArrayList<World> level (containing the 2 levels; LevelOne (ArrayList index 0) and LevelTwo (ArrayList index 1) -isOfClass is a boolean in the "WorldManager"

    public static boolean isOfClass(World w, Class c)
    {
        return w.getClass() == c;
    }
danpost danpost

2012/11/16

#
I think the main fault is in the 'changeLevel' method, at line 3. You only have two elements in the array, but you are executing the loop three times. Change 'i <= WorldManager.level.size()' to 'i < WorldManager.level.size()'. If the size is two, then element 0 and 1 would be the two elements. In fact, if you only have two world, then you can only change worlds once, meaning you should use 'i < WorldManager.level.size() - 1'. An easier way to control the levels is with a 'static int levelNum' variable in the WorldManager class, which can signify which element in the array of worlds is the current world (or the one to change to). Your 'changeLevel' method could be simply:
public void changeLevel(tempRocket)
{
    getWorld().removeObject(tempRocket);
    WorldManager.levelNum++;
    if (WorldManager.levelNum < WorldManager.level.size()) setWorld(WorldManager.level.get(WorldManager.levelNum));
}
With the 'levelNum' to keep track of what world you are in, you do not need to search for what class you are currently in; and there is no need for the 'isOfClass' method.
benessto benessto

2012/11/18

#
Thanks you very much and also a good hint to use a static int!
You need to login to post a reply.