索引数组超出范围异常?

时间:2015-04-01 20:34:49

标签: java

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

1.Line 61 :( Class Sprite)

private void load() {
    for (int y = 0; y < SIZE; y++) {
        for (int x = 0; x < SIZE; x++) {
            pixels[x + y * SIZE] = sheet.pixels[(x + this.x) + (y + this.y) * sheet.SIZE];      //Here is the error.
        }
    }
}

2.Line 43 :( Class Sprite)

public Sprite(int size, int x, int y, SpriteSheet sheet) {
    SIZE = size;
    pixels = new int[SIZE * SIZE];
    this.x = x * size;
    this.y = y * size;
    this.sheet = sheet;
    load();                                     //Here is the error.
}

3。第16行:(类精灵)

public static Sprite spawn_grass = new Sprite(16, 0, 3, SpriteSheet.spawn_level);   //Here is the error.
public static Sprite spawn_stone = new Sprite(16, 0, 2, SpriteSheet.spawn_level);
public static Sprite spawn_water = new Sprite(16, 1, 3, SpriteSheet.spawn_level);
public static Sprite spawn_wall = new Sprite(16, 1, 1, SpriteSheet.spawn_level);
public static Sprite spawn_wall2 = new Sprite(16, 1, 2, SpriteSheet.spawn_level);
public static Sprite spawn_floor = new Sprite(16, 0, 0, SpriteSheet.spawn_level);
  1. 第23行:(班主任)

    public Player(int x, int y, Keyboard input) {
    this.x = x;
    this.y = y;
    this.input = input;
    sprite = Sprite.player_forward;          //Here is the error.
    

    }

  2. 5.Line 46 :(类游戏)

    public Game() {
        Dimension size = new Dimension(width * scale, height * scale);
        setPreferredSize(size);
    
        screen = new Screen(width, height);
        frame = new JFrame();
        key = new Keyboard();
        level = Level.spawn;
        player = new Player(16 * 6, 16 * 4, key);       //Here is the error.
    
        addKeyListener(key);
    }
    

    我该怎么办?救命啊!

1 个答案:

答案 0 :(得分:0)

而不是数组使用数组列表,因为load()仅在构造函数中(我只能看到一次),您可以附加元素而不是为数组找到正确的索引。因此,如果您附加列表,则永远不会出现越界错误。

数组列表代码:

ArrayList<Integer> list = new ArrayList<>(); //init list

list.add(); //put same thing you would with array in ()

如果错误仍然存​​在,则问题是sheet.pixels[],但是我无法看到该代码,所以如果这是问题我无法帮助你,直到我看到它被初始化的地方