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

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

我有一个二维阵列:

  1. public int[][] intmap =
  2. {
  3. {0, 0, 0, 0, 0},
  4. {0, 1, 2, 0, 0},
  5. {0, 0, 2, 0, 0},
  6. {0, 3, 0, 0, 0},
  7. {0, 0, 0, 3, 3}
  8. };

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

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

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

pb3s4cty

pb3s4cty1#

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

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

}

相关问题