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?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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.