为什么我得到一个数组索引超出范围的异常?

时间:2015-03-30 18:26:08

标签: java

根据调试屏幕,错误出现在:

1.Line 16 :( Class RandomLevel)

protected void generateLevel() {
    for (int y = 0; y < height; y++) {
        for (int x = 0; y < width; x++) {
            tiles[x + y * width] = random.nextInt(4);   //Here is the error.
        }
    }
}

2.Line 15 :( Class Level)

public Level(int width, int height) {
    this.width = width;
    this.height = height;
    tiles = new int[width * height];
    generateLevel();                               //Here is the error.
}

3。第10行:( Class RandomLevel)

public RandomLevel(int width, int height) {
    super(width, height); // Here is the error.
}

4。第43行:(类游戏)

public Game() {
    Dimension size = new Dimension(width * scale, height * scale);
    setPreferredSize(size);

    screen = new Screen(width, height);
    frame = new JFrame();
    key = new Keyboard();
    level = new RandomLevel(64, 64);                  // Here is the error.

    addKeyListener(key);
}

5.Line 124 :(类游戏)

public static void main(String[] args) {
    Game game = new Game();                           // Here is the error.
    game.frame.setResizable(false);
    game.frame.setTitle(game.title);
    game.frame.add(game);
    game.frame.pack();
    game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.frame.setLocationRelativeTo(null);
    game.frame.setVisible(true);

    game.start();
}

我该怎么办?我理解异常是什么,但我不知道它为什么会出现。帮助

3 个答案:

答案 0 :(得分:7)

内部for循环的条件错误。

for (int x = 0; y < width; x++) {

您正在循环x,但您的情况再次涉及y。尝试

for (int x = 0; x < width; x++) {

答案 1 :(得分:1)

你有

for (int x = 0; y < width; x++) {
你打算

吗?
for (int x = 0; x < width; x++) {

答案 2 :(得分:1)

你有两个错误:

1)

 for (int x = 0; y < width; x++) {

将y更改为x

2)

tiles = new int[width * height];

  tiles[x + y * width] = random.nextInt(4);   //Here is the error.

这将进入

tiles[width+height*width] 

将导致错误,更改

 tiles = new int[width * height];

tiles = new int[width + width * height];