首页 > 解决方案 > Showing java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 in some test cases?

问题描述

Code:

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;
        
    }
}

标签: javaarraysmatrixmultidimensional-arraydsa

解决方案


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

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
    }
}

推荐阅读