用2个arraylists抛出IndexOutOfBoundsException的Java游戏?

时间:2014-10-19 02:27:51

标签: java arraylist indexoutofboundsexception

我在java中制作了一个相当简单的游戏,我不断从我的arraylist中获取这个IndexOutofBoundsException。我有1个创建"子弹"的arraylist,另有一个存储" missles"。该程序运行,我可以发射子弹大约5秒钟,然后冻结给我这个错误。我不确定发生了什么。

这是我创建数组列表的Canvas类的一部分。

 ArrayList ms = craft.getMissles();
    ArrayList bs = craft.getBullets();

    for (int i = 0; i < ms.size(); i++ ) {
        Missle m = (Missle) ms.get(i);
        g2d.drawImage(m.getImage(), m.getX(), m.getY(), this);
    }
     for (int b = 0; b < bs.size(); b++ ) {
        Bullet a = (Bullet) bs.get(b);
        g2d.drawImage(a.getImage(), a.getX(), a.getY(), this);
    }

    Toolkit.getDefaultToolkit().sync();
    g.dispose();
}


public void actionPerformed(ActionEvent e) {
    ArrayList ms = craft.getMissles();
    ArrayList bs = craft.getBullets();

    for (int i = 0; i < ms.size(); i++) {
        Missle m = (Missle) ms.get(i);
        if (m.isVisible()) 
            m.move();
        else ms.remove(i);
    }
    for (int b = 0; b < bs.size(); b++) {
        Bullet a = (Bullet) bs.get(b);
        if (a.isVisible()) 
            a.move();
        else ms.remove(b);
    }

    craft.move();
    repaint();  
}

这是我的Craft类的一部分,它具有导弹的动作。我在上面声明它们,当我只有导弹部件时,代码工作正常。当我添加第二个arraylist时出现错误。

 public Craft() {
    ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));
    image = ii.getImage();
    missles = new ArrayList();
    bullets = new ArrayList();
    x = 1000;
    y = 60;
}
private ArrayList missles;
private ArrayList bullets;
private final int CRAFT_SIZE = 85;
private final int CRAFT_SIZE2 = 20;

public void move() {
    x += dx;
    y += dy;
}

public int getX() {
    return x;
}

public int getY() {
    return y;
}

public Image getImage() {
    return image;
}

public ArrayList getMissles() {
    return missles;
}
public ArrayList getBullets() {
    return bullets;
}

public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
        dx = -2;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 1;
    }

    if (key == KeyEvent.VK_UP) {
        dy = -2;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 3;
    }
    if (key == KeyEvent.VK_SPACE) {
        fire();
    }
    if (key == KeyEvent.VK_V) {
        fire2();
    }

}

public void fire() {
    missles.add(new Missle(x + CRAFT_SIZE, y + CRAFT_SIZE/2));
}

public void fire2() {
    bullets.add(new Bullet(x + CRAFT_SIZE2, y + CRAFT_SIZE/2));
}

1 个答案:

答案 0 :(得分:0)

我至少发现了一个错误:

else ms.remove(b);

应该是

else bs.remove(b);