数组处理的OutOfBounds异常

时间:2013-12-21 03:00:32

标签: java arrays indexoutofboundsexception

我试图通过此循环将值传递给GUI进行编辑:

public void update(String key) {
    for (int y = 0; y < pixels.length; y++) {
        for (int x = 0; x < pixels[y].length; x++) {
            if (pixels[y][x] == 2) {
                if (key.equals("up")){
                    pixels[y][x] = 1;
                    pixels[y - 1][x] = 2;
                } else if (key.equals("down")) {
                    pixels[y][x] = 1;
                    pixels[y + 1][x] = 2;
                } else if (key.equals("left")) {
                    pixels[y][x] = 1;
                    pixels[y][x - 1] = 2;
                } else if (key.equals("right")) {
                    pixels[y][x] = 1;
                    pixels[y][x + 1] = 2;
                }
            }
        }
    }
    gui.repaint();
}

key.equals("up")key.equals("left")分支没有问题,但key.equals("down")key.equals("right")没有。

我正在使用的数组是25x25

pixels = new int[][]{ 
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } 
};

确切的错误是:Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 25

我试图对此进行调试,但我无法弄明白。

编辑: 我已将key.equals("down")key.equals("right")中的代码更新为:

pixels[y][x] = 1;
if (y + 1 != 25) {
    pixels[y + 1][x] = 2;
}
pixels[y][x] = 1;
if (x + 1 != 25) {
    pixels[y][x + 1] = 2;
}

然而,它在这两个分支上给出了一个恒定的输出(不需要),而在另外两个分支上没有。为什么?

1 个答案:

答案 0 :(得分:1)

所以,你按下,循环遍历整个阵列 - 当你击中中心时,你“移动”2“向上”并将中心设置为1 - 然后你继续迭代0的数组。细

但是,你向下按,同样的事情发生了 - 除了你“向下移动”2“向下”你继续向下通过数组 - 所以你再次找到2 ,然后再将它向下移动 - 依此类推,直到你试图将它移过边界。

您认为您在启动循环时拥有数组的读一致视图,但您没有。每次更改都会立即显示。

最简单的解决方案可能是保留两个阵列副本;从第一个读取,但对第二个进行更改;然后丢弃第一个并制作新副本以处理下一个按键。