java - java中如何将两个多维数组相加?

标签 java arrays multidimensional-array

public class MatrixAddition {

    public static void main(String[] args) {

        int ar1[][] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } };
        int ar2[][] = { { 8, 7, 6 }, { 5, 4, 3 }, { 2, 1, 0 } };

        addArray(ar1, ar2);

    }

    private static void addArray(int[][] tmp1, int[][] tmp2) {
        int[][] sum = {};
        System.out.println(" ");
        System.out.println("The sum of the two matrices is");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                sum[i][j] = tmp1[i][j] + tmp2[i][j];
                System.out.print(sum[i][j] + "  ");
            }

        }

    }

}

输出:

The sum of the two matrices is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

最佳答案

您唯一的问题是您没有正确初始化 sum 数组:

int[][] sum = new int[tmp1.length][tmp1[0].length];

将其初始化为空数组。

关于java - java中如何将两个多维数组相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27679816/

相关文章:

java - 致命异常 : java. lang.UnsupportedOperationException:无法解析索引 6 处的属性:TypedValue{t=0x2/d=0x101009b a=1}

java - 分割字符串java

java.io.FileNotFoundException(打开的文件太多)

java - 使用 for-each 循环或使用迭代器迭代 JSON 数组 (Android Studio)

python - Python中的矩阵转置

Java Swing 设置 "actual"帧大小(内部)

c - 字符串数组上的基本 qsort 在 qsort() 中崩溃

c - 何时在 C 中使用可变长度数组,但何时使用动态分配?

arrays - 生成伪语言的 C 程序 - 全局 3D 数组太大(段错误)?

c - 在矩阵中查找正方形