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

2022/1/17

Hi i am programming a game for school project

pascal2233 pascal2233

2022/1/17

#
My Problem is that im stuck with fixing array list error out of bounds. I have made an array list with a for loop creating the highest possibly needed count of actor track and then a case switch that checks the direction to where it should put these objects wich only spawns the needed one into the world.
public void drawRails(int directionIn)
    {
        Track[] track = new Track[68880];
        for(int y=track.length;y<track.length*2;y=y+20)
        {
            track[y] = new Track();
        }
        
        switch(directionIn)
        {
            case 1:
                for(int q=track.length;q<track.length*2;q=q+20)
                {
                    addObject(track[q], q, yDrawDepot);
                }
            ;
            case -1:
                for(int w=track.length;w<track.length*2;w=w+20)
                {
                    addObject(track[w], w, yDrawDepot);
                }
            ;
            
            case 2:
                for(int e=track.length;e<track.length*2;e=e+20)
                {
                    addObject(track[e], xDrawStation, e);
                }
            ;
            case -2:
                for(int f=track.length;f<track.length*2;f=f+20)
                {
                    addObject(track[f], f, yDrawDepot);
                }
            ;
        }
    }
//java.lang.ArrayIndexOutOfBoundsException: Index 68880 out of bounds for length 68880

// width is 1641 height is 841 divide (1641*841)/20 = array lenght (-margin)

//at Game.drawRails(Game.java:38)     track[y] = new Track();
//at Game.prepare(Game.java:87)     one of the cases in the switch
//at Game.<init>(Game.java:30)    prepare call
pascal2233 pascal2233

2022/1/17

#
java.lang.ArrayIndexOutOfBoundsException
danpost danpost

2022/1/17

#
pascal2233 wrote...
java.lang.ArrayIndexOutOfBoundsException
Your for loops are set to iterate twice the length of the array. Meaning, you are creating more Track objects than the array can hold. That is, your array length is 68880 and you try to place 137760 Track objects in that array. It can't be done. Hence the error once your loop counter reaches 68880, since the last element is indexed at 68879.
You need to login to post a reply.