将2D数组与数字进行比较的Java给出了例外

时间:2015-06-15 01:14:07

标签: java arrays multidimensional-array

我试图将2D数组与数字进行比较,但它会抛出异常。

代码

import org.newdawn.slick.Color;

public class Main {

    public static int[][] map = {{0, 2, 1, 3, 4, 1, 1, 3, 4, 1, 3, 5, 1},
    {1, 2, 1, 3, 4, 1, 1, 3, 4, 1, 3, 5, 1},
    {2, 2, 1, 3, 4, 1, 1, 3, 4, 1, 3, 5, 1},
    {3, 2, 1, 3, 4, 1, 1, 3, 4, 1, 3, 5, 1},
    {4, 2, 1, 3, 4, 1, 1, 3, 4, 1, 3, 5, 1},
    {5, 2, 1, 3, 4, 1, 1, 3, 4, 1, 3, 5, 1},
    {6, 2, 1, 3, 4, 1, 1, 3, 4, 1, 3, 5, 1},
    {7, 2, 1, 3, 4, 1, 1, 3, 4, 1, 3, 5, 1}};

    public static void main(String args[]) {
        int I = 0;
        int II = 0;

        for (int y = 0; y < 7; y++) {

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

                if (map[x][y] == 0) {
                    g.setColor(Color.blue);
                    g.fillRect(I, II, 100, 100);
                }
                if (map[x][y] == 1) {
                    g.setColor(Color.orange);
                    g.fillRect(I, II, 100, 100);
                }
                if (map[x][y] == 2) {
                    g.setColor(Color.white);
                    g.fillRect(I, II, 100, 100);
                }
                if (map[x][y] == 3) {
                    g.setColor(Color.red);
                    g.fillRect(I, II, 100, 100);
                }
                if (map[x][y] == 4) {
                    g.setColor(Color.green);
                    g.fillRect(I, II, 100, 100);
                }
                if (map[x][y] == 5) {
                    g.setColor(Color.gray);
                    g.fillRect(I, II, 100, 100);
                }
                I = x * 100;
                I = y * 100;
            }
        }
    }
}

抛出的例外是java.lang.ArrayIndexOutOfBoundsException: 8 这是一个裸骨砖图系统,如果你想测试这个你需要slick2D并需要把它放在渲染循环中。

1 个答案:

答案 0 :(得分:3)

这是因为您尝试访问行8并且您只有最大位置7

请记住,行和列的索引从位置0开始,以长度-1结束。

此外,您必须记住,数组的第一个位置(在您的情况下为x)是行,而y是列。 < / p>

array[rows][columns]

因此,您必须更改循环中变量的顺序。像这样:

for(int x = 0; x < map.length; x++){

    for(int y = 0; y < map[x].length; y++){

其余代码可能就像你上面一样。

我希望它会对你有所帮助!