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

2021/6/13

Index Out of Bounds Error

Billykid679 Billykid679

2021/6/13

#
For some reason when I use the getObjects for the Plane class, after a new plane is added, a Index out of bounds error occurs. Can someone please help me?
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Bomb here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Bomb extends Actor
{
     
    int timer = 0;
    int starttimer = 0;
    
    int i = 0;
    

    
    /**
     * Act - do whatever the Bomb wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        
        Bombing();
        setRotation(60);
        move(4);

    }    
    public void Bombing()
    {
        Plane plane = (Plane)getWorld().getObjects(Plane.class).get(0+i);       
        int PlaneY = plane.getY(); 
        int PlaneX = plane.getX();

        if(i<=5)
        {        
            if(PlaneX >= 200)
            {
                timer++;
                if(PlaneX >= 600)
                {
                    i++;
                }
                if (timer >= 100)
                {

                    getWorld().addObject(new Bomb(),PlaneX, PlaneY);

                    timer = 0;
            
                }
                

            }
            edgeHit();
        }
    }
    
    public void edgeHit()
    {
        if(isAtEdge())
        {

            getWorld().removeObject(this);

        }
    }

}
Super_Hippo Super_Hippo

2021/6/13

#
That’s not looking right. The code will fail with an error message if you have less than 6 planes in your world. But there is a more general problem with your code: The creation of bombs should happen in the Plane class, not in the Bomb class.
Billykid679 Billykid679

2021/6/13

#
Thanks a lot, I was stuck trying to make it work in the bomb class when I could have just put it in the plane class like you said.
You need to login to post a reply.