java二维数组中的移动字符及其异常

but5z9lq  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(365)

我有一个二维阵列:

public int[][] intmap =
        {
                {0, 0, 0, 0, 0},
                {0, 1, 2, 0, 0},
                {0, 0, 2, 0, 0},
                {0, 3, 0, 0, 0},
                {0, 0, 0, 3, 3}
        };

如果下一步是其中一步,我想打印一条警告消息。我试图使用一个例外,因为我不想超出范围。下面是一个方向的示例(来自我的代码):

public void goRight() {
    try {
        if (intmap[i][j + 1] != 2 && intmap[i][j + 1] != 3) {
            intmap[i][j] = previousNumber;
            previousNumber = intmap[i][j + 1];
            intmap[i][j] = 1;
        } else {
            System.out.println("You can not move here!");
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("You can not move outside the the map!");
    }
}

我试着用 ++j 开始时没有 if() 效果不错。它没有让我走出Map,但我想解决“2号和3号”的问题。所以我做了一个 if(){}else{} 但效果不太好。我朋友告诉我应该用 j+1 而不是 ++j 但在这种情况下,角色不会移动。 previousNumber 是一个int,我把数字1存储在这里。默认情况下,我给出 int previousNumber = 0 . 我可以调用direction方法并打印出数组。谢谢你的帮助!

pb3s4cty

pb3s4cty1#

我曾经 ++j 而不是 j+1 在if内部。

public void goRight() {
try {
    if (intmap[i][j + 1] != 2 && intmap[i][j + 1] != 3) {
        intmap[i][j] = previousNumber;
        previousNumber = intmap[i][++j];
        intmap[i][j] = 1;
    } else {
        System.out.println("You can not move here!");
    }
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("You can not move outside the the map!");
}

}

相关问题