[英]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.