显示java.lang.ArrayIndexOutOfBoundsException:在某些测试案例中,索引2超出了长度2的范围?

问题描述

代码

static void exchangeColumns(int matrix[][])
{    
    int i;
    int n = matrix[0].length;
    for (i=0;i<n;i++){
    
        int temp = matrix[i][0];
        matrix[i][0] = matrix[i][n-1];
        matrix[i][n-1] = temp;
        
    }
}

解决方法

您使用了错误的方式来迭代多维数组。请使用以下方式遍历数组。

for (int i = 0; i < matrix.length; ++i) {
    for(int j = 0; j < matrix[i].length; ++j) {
        System.out.println(matrix[i][j]); // Here you can place your logic by accessing the array elements
    }
}