簡體   English   中英

我的arraylist出現IndexOutOfBoundsException,我在做什么錯?

[英]I'm getting an IndexOutOfBoundsException with my arraylist, what am I doing wrong?

此類在我正在編寫的基本上是“太空侵略者”游戲的程序中。 由於某種原因,我得到了Exceptions ,但我不明白為什么要得到它們。

這是有問題的課程,但是如有必要,我可以發布所有代碼:

public class GamePanel extends JPanel {

    Launcher launcher1;
    Background bground1;
    Shot shot;
    public ArrayList<Shot> shots;
    public int numShots;
    public static int counter;

    public GamePanel() throws IOException {
        super();
        this.shots = new ArrayList<>();
        this.numShots = 0;
        launcher1 = new Launcher();
        bground1 = new Background();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(bground1.background, 0, 0, getWidth(), getHeight(), null);
        g.drawImage(launcher1.baldEagleImage, launcher1.getLxCoord(), launcher1.lyCoord, null);//paint the launcher
        while (counter == 1) {
            for (int i = 0; i < shots.size(); i++) {
                g.drawImage(shots.get(i).mcDShotImage, shots.get(i).staticXLauncherCoord, shots.get(i).getSyCoord(), null);
            }
        }
    }

    public void move(GamePanel gamePanel) {
        launcher1.moveX();
        if (numShots > 0) {
            moveShot();
        }
        repaint();
    }

    public void moveShot() {
        for (int i = 0; i < numShots; i++) {//loop to move all the shots
            if (shots.get(i).getSyCoord() > 10) { // THIS IS THE ISSUE, but I don't know why
                counter = 1;
                shots.get(i).moveY();
                repaint();
            } else {
                counter = 0;
                shots.remove(i);
                repaint();
            }
        }
    }

    public void createShots() {
        try {
            for (int j = 0; j < numShots; j++) {
                shots.add(new Shot());
            }
        } catch (IOException | IndexOutOfBoundsException e) {
            System.out.println("caught an exception" + e);
        }
    }
}

問題出在這段代碼中:

} else {
    counter = 0;
    shots.remove(i);
    repaint();
}

您無需調整numShots即可從shots刪除項目,從而在后續迭代之一中導致索引超出范圍異常。

為了解決這個問題,要么添加numShots--else分支,或者使用內置的size()返回元素的個數在一個列表,而不是方法:不像numShots您需要維護, shots.size()永遠不會與實際計數“不同步”。

在上面的代碼行中,很明顯的問題是numShots是> shots.size()(因為您還刪除了鏡頭。由於我無法在您增加numShots的位置,因此在這段代碼中,一個簡單的(盡管不是請從邏輯角度確定),如下更改您的for循環:

for (int i = 0; i < shots.size(); i++)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM