函数来计算2d数组中每列的平均值线程“main”java.lang.arrayindexoutofboundsexception中出现异常:3

apeeds0o  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(316)

这个问题在这里已经有答案了

是什么导致java.lang.arrayindexoutofboundsexception以及如何防止它(26个答案)
上个月关门了。
我有一个计算每列平均值的函数,但当我运行它时,它会给出:exception in thread“main”java.lang.arrayindexoutofboundsexception:3

// function to calculate the average value of columns of the given matrix
static void povprecje_stolpci(double matrix[][]) {
    int i, j;
    double zbir = 0, prosek = 0; // prosek - variable for average
    for (i = 0; i < matrix.length; i++) {
        for (j = 0; j < matrix[i].length; j++) {
            zbir = (int) (zbir + matrix[j][i]); // zbir variable to calculate the sum of the elements in each columns
        }
        prosek = (int) (zbir / matrix[i].length); // average of the columns
        System.out.print(prosek); // printing the average
        zbir = 0; // setting the sum to 0 for the next element 
        System.out.print(" ");
    }

}
8i9zcol2

8i9zcol21#

问题在于 zbir = (int) (zbir + matrix[j][i]); 您需要更改的代码部分:
因为在第一个循环中遍历数组的行,在内部循环中遍历列

zbir = (int) (zbir + matrix[i][j]);

完整代码:

static void povprecje_stolpci(double matrix[][]) {
    int i, j;
    double zbir = 0, prosek = 0; // prosek - variable for average
    for (i = 0; i < matrix.length; i++) {
        for (j = 0; j < matrix[i].length; j++) {
            zbir = (int) (zbir + matrix[i][j]); // zbir variable to calculate the sum of the elements in each
                                                // columns
        }
        prosek = (int) (zbir / matrix[i].length); // average of the columns
        System.out.print(prosek); // printing the average
        zbir = 0; // setting the sum to 0 for the next element
        System.out.print(" ");
    }
}

相关问题