0

当我运行应用程序并触摸位图时,有时应用程序崩溃

这是错误:

at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at com.example.Game.GFXSurface$GameSurface.run(GFXSurface.java:135)
at java.lang.Thread.run(Thread.java:864)

以及它崩溃的代码,如果我删除balls.remove并且balls.add一切正常,但它不会生成新球,并且在运行方法中一切正常,remove并且add

@Override
public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    GameSurface gamesurface = new GameSurface(this);
    x = event.getX();
    y = event.getY();
    Bitmap ball = BitmapFactory.decodeResource(getResources(),
            R.drawable.ic_launcher);
    for (int i = 0; i < 4; i++)
        if (ourSurfaceView.MouseOnDot(ball) && x >= ballX[i]
                && x <= ballX[i] + 72) {
            balls.remove(i);
            balls.add(i, gamesurface.RandomBall());
            ChangingY[i] = 0;
            if (speed <= 7)
                speed += 0.1;
        }
    return false;
}

这是balls.get的方法

@Override
        public void run() {

            for (int j = 0; j < 4; j++) {
                balls.add(j, RandomBall());
            }

            while (isRunning) {
                if (!ourHolder.getSurface().isValid())
                    continue;

                Canvas canvas = ourHolder.lockCanvas();
                canvas.drawRGB(02, 02, 150);

                for (int i = 0; i < 4; i++) {
                    ballX[i] = i * 155;
                    canvas.drawBitmap(balls.get(i), ballX[i], ChangingY[i],
                            null);
                    if (ChangingY[i] <= canvas.getHeight()) {
                        ChangingY[i] += 1 * speed;
                    } else if (ChangingY[i] > canvas.getHeight()) {
                        ChangingY[i] = 0;
                        if (speed <= 5)
                            speed += 0.25;
                        balls.remove(i);
                        balls.add(i, RandomBall());

                    }
                }

                // }

                ourHolder.unlockCanvasAndPost(canvas);
            }
        }
4

1 回答 1

2

错误意味着您用于访问 ArrayList 的索引大于 ArrayList 的大小。

尝试代替 for (int i = 0; i < 4; i++) 使用 for (int i = 0; i < balls.size(); i++)

或者当您使用 balls.remove(i) 时,首先检查 i < balls.size

于 2012-09-15T10:58:06.753 回答