Showing java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 in some test cases?

huangapple go评论70阅读模式
英文:

Showing java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 in some test cases?

问题

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;

    }
}
英文:

Code:

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

答案1

得分: 1

你正在错误地迭代多维数组。请使用以下方法遍历您的数组。

for (int i = 0; i < matrix.length; ++i) {
    for(int j = 0; j < matrix[i].length; ++j) {
        System.out.println(matrix[i][j]); // 在此处您可以通过访问数组元素来放置您的逻辑
    }
}
英文:

You are using a wrong way to iterate the multi-dimensional array. Please use the following way to iterate through your array.

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

huangapple
  • 本文由 发表于 2020年10月20日 19:35:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64444313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定