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

2017/1/20

How to stop array from going out of bounds.

nat12 nat12

2017/1/20

#
I have created a 2D array that contains the X and Y coordinates for the spawning method. That works great, however after all levels have been done the terminal pops up with "java.lang.ArrayIndexOutOfBoundsException: 4" Variables declared:
  int level = 0;
    int score = 0;
    int enemyHP = 0;
    int [][] enemyLOC= {{800,800,0,0},{50,800,0,800}};
    int i = 0;
    int n = 0;
Spawning method:
    public void mmethod()
    {
        while(getObjects(EnemyShip.class).isEmpty())
        {
             for (i = 0; i < level; i++)
             {
                    for (n = 0; n < 2; n++) 
                        addObject(new EnemyShip(), (enemyLOC[0][i])-(n*60),(enemyLOC[1][i])-(n*60)); // xRIGHT yTOP
             }
        }
    }
I had also tried to make an if statement before the first 'for loop' "if (i <4) else Greenfoot.stop()" but, then it would run into an infinite loop instead of stopping, no idea why.
danpost danpost

2017/1/20

#
Just place the following line before the 'while' statement:
if (level > 3) return;
nat12 nat12

2017/1/20

#
Wow so simple, thank you very much. However, I have another problem. On level 3 and 4, the top left EnemyShip classes spawn on top of each other, but the other spawns are perfectly fine and are separated by 60 pixels, like I specified in the addObject. http://prntscr.com/dy4022 What it looks like. This is my level method (inside act), might be something with that.
    public void act()
    {  
        level = (score+6)/6;
        mmethod();
    }
danpost danpost

2017/1/20

#
Change the '0's in your 'enemyLOC' array to something like '50's or '60's.
nat12 nat12

2017/1/20

#
Yeah, I just noticed that it's something about the 0,0. However, would you mind telling me as to why this is different from the other locations, such as 800,800 which is basically the same location but on the opposite side.
danpost danpost

2017/1/20

#
nat12 wrote...
would you mind telling me as to why this is different from the other locations, such as 800,800 which is basically the same location but on the opposite side.
You are placing two enemies near the same location. The second one added into the world is placed using the same initial coordinates as the first but with a location offset of (-60, -60). When the initial location is (0, 0), well ... I think you can figure it out.
nat12 nat12

2017/1/20

#
Oh... I always make it sound more complicated than it actually is. Thanks once again.
You need to login to post a reply.