【问题标题】:ArrayIndexOutOfBoundsException, only prints first lineArrayIndexOutOfBoundsException,只打印第一行
【发布时间】:2014-03-16 04:19:48
【问题描述】:

我正在用 Java 制作地牢游戏。我创建了一个将地图存储在二维数组中的方法。数组如下所示:

[[#, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #],
[#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #],
[#, ., ., ., ., ., ., G, ., ., ., ., ., ., ., ., E, ., #],
[#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #],
[#, ., ., E, ., ., ., ., ., ., ., ., ., ., ., ., ., ., #],
[#, ., ., ., ., ., ., ., ., ., ., G, ., ., ., ., ., ., #],
[#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #],
[#, ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., ., #],
[#, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #]]

我现在正在尝试编写一个函数,以便可以在游戏中打印出地图。到目前为止,我想出了这个:

public void printMap(char[][] map) {
    for (int i = 0; i < map.length; i++) {
        for (int j = 0; j < map[i].length; i++) {
            System.out.print(map[i][j]);
        }
    }
}

但是,在打印出第一行后,我收到了此错误消息。

#########Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9

为什么我会收到此错误消息?以后如何预防?

【问题讨论】:

  • 你认为这个错误意味着什么?
  • @JonathonReinhart 不要读博客,写一篇!挫折感。

标签: java arrays printing multidimensional-array indexoutofboundsexception


【解决方案1】:

您在嵌套的 for 循环中递增 i 而不是 j:

  for(int j=0; j < world[i].length; i++){
                System.out.print(world[i][j]);
            }

改为:

for(int j=0; j < world[i].length; j++){
            System.out.print(world[i][j]);
        }

【讨论】:

    【解决方案2】:

    您在 j 循环中增加 i 而不是 j。然而,我不明白为什么它会在一行之后就崩溃。我想你的第一个数组中不仅仅是一个项目,不是吗?

    【讨论】:

      【解决方案3】:
      for(int j=0; j < world[i].length; i++){
      //      ^    ^                    ^
      //      J    J                    I <- No! Bad dog :-)
      

      您可能希望使变量更加一致。

      通过在j 循环中增加i,您几乎可以保证您将超出world 数组的末尾(“near”,因为如果“sub- arrays" 的大小为零,但根据您的输入数据,这里不太可能出现这种情况)。

      【讨论】:

        猜你喜欢
        • 2015-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-04
        • 2011-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多