【问题标题】:Why Java multidimensional arrays ge ArrayIndexOutOfBoundsException when the first array is [2] or more? [duplicate]当第一个数组为[2]或更多时,为什么Java多维数组ge ArrayIndexOutOfBoundsException? [复制]
【发布时间】:2017-11-20 20:45:23
【问题描述】:

我正在学习 Java 的多维数组。当我设置 arr ={{1,2,3},{4,5,6}} 和 int x = arr[2 or more][any digit] 时,ArrayIndexOutOfBoundsException 出来了。

public class Array {

    public static void main(String[] args) {

        int [][] arr= { {4,5,6,7},{1,2,3,8}};
        int x;

        for(int a= 0,b= 0;a<= 3 && b<= 3; a++, b++){
            try {
                x = arr[a][b];
                System.out.println("a = "+ a + " b = "+ b +"\n"+ x +"\nCorrect----------------------");
            }catch(ArrayIndexOutOfBoundsException e) {
                System.out.println("a = "+ a + " b = "+ b +"\nERROR------------------");
            }
        }   

    }

}

结果:

a = 0 b = 0
4
Correct----------------------
a = 1 b = 1
2
Correct----------------------
a = 2 b = 2
ERROR------------------
a = 3 b = 3
ERROR------------------

【问题讨论】:

  • 这是 ArrayIndexOutOfBoundsException 2
  • 因为数组只有两个元素:第一个在索引 0 = {4,5,6,7},第二个在索引 1 = {1,2,3,8};索引 2 或以上没有任何剩余

标签: java arrays exception multidimensional-array


【解决方案1】:

您的 for 循环经过 4x4 范围,但您的数组是 2x4。

二维数组是数组的数组。第一个索引是您访问的数组。

你有两个数组,[4,5,6,7] 和 [1,2,3,8]

访问 arr[2] 意味着给了我第三个数组,而你没有第三个数组

【讨论】:

    【解决方案2】:

    int [][] arr= { {4,5,6,7},{1,2,3,8}}; 定义了一个包含 2 个int[] 的数组:

    arr[0]={4,5,6,7}
    arr[1]={1,2,3,8}
    

    所以arr[2] 会抛出异常。

    【讨论】:

      猜你喜欢
      • 2013-06-29
      • 2019-02-09
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 2011-02-22
      • 2015-06-09
      • 2016-03-25
      相关资源
      最近更新 更多