首页 > 解决方案 > 矩阵乘法中的越界异常

问题描述

我写了这段代码。

public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.println("Please enter the rows \"then\" columns of the first array: ");
        int a = console.nextInt();
        int b = console.nextInt();
        int[][] arr1 = new int[a][b];
        System.out.println("Please enter the rows \"then\" columns of the second array: ");
        int c = console.nextInt();
        int d = console.nextInt();
        int[][] arr2 = new int[c][d];
        if (b != c) {
            System.out.println("these two matrices can't be multiplied!!");
        } else {
            int[][] mult = new int[a][c];
            System.out.println("Please enter the elements of the first array : ");
            for (int i = 0; i < a; i++) {
                for (int j = 0; j < b; j++) {
                    arr1[i][j] = console.nextInt();
                }
            }
            System.out.println("Please enter the elements of the second array : ");
            for (int i = 0; i < c; i++) {
                for (int j = 0; j < d; j++) {
                    arr2[i][j] = console.nextInt();
                }
            }
            int sum = 0;
            for (int i = 0; i < a; i++) {
                for (int j = 0; j < d; j++) {
                    for (int k = 0; k < c; k++) {
                        sum += arr1[i][k] * arr2[k][j];
                        mult[i][j] = sum;
                    }
                    sum = 0;
                }

            }
            for(int i=0;i<a;i++){
                for(int j=0;j<d;j++) {
                    System.out.print(mult[i][j] + "  ");
                }
                System.out.println("");
            }
      }
    }
}

当我运行它时,它说java.lang.ArrayIndexOutOfBoundsException.

不知道为什么,谢谢帮忙。

标签: java

解决方案


据我所知,这可能是问题所在:int[][] mult = new int[a][c],应该是new int[a][d]

P / s:如果您可以格式化代码的第一部分会更好


推荐阅读