这个课程是在我正在编写的游戏程序中,基本上是太空入侵者。我出于某种原因得到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);
}
}
}
答案 0 :(得分:4)
问题在于这段代码:
} else {
counter = 0;
shots.remove(i);
repaint();
}
您在不调整shots
的情况下从numShots
删除项目,导致后续迭代之一的索引超出范围异常。
要解决此问题,请在numShots--
分支中添加else
,或使用内置的size()
方法来返回列表中元素的数量:与{{1不同你需要维护的,numShots
永远不会得到&#34;不同步&#34;与实际计数。
答案 1 :(得分:1)
在上面的代码行中,显而易见的是问题是numShots是&gt; shots.size()(因为你也删除了镜头。 因为我无法在增加numShots的位置,所以在这段代码中,一个简单的(虽然从你的逻辑角度不确定)改变你的for循环如下:
for (int i = 0; i < shots.size(); i++)