Java 矩阵乘法 ArrayIndexOutOfBounds 异常

Java Matrix multiplication ArrayIndexOutOfBounds Exception

我刚开始自己​​学习 Java,我正在尝试将我在大学里从 C++ 获得的不同程序变成 Java。 我想使用一些 void 方法对矩阵进行乘法运算,但是在尝试像 2-2 2-1 这样的矩阵相乘时,我经常遇到这个异常 (java.lang.ArrayIndexOutOfBoundsException), 3-2 2-3 等 该程序适用于 3-3 3-3、4-4 4-4 等矩阵,但当变量不相同时会失败。不明白我哪里错了,有人可以帮忙吗?

进口java.util.Scanner; public class 矩阵乘法 {

static Scanner sc = new Scanner(System.in);

public static void main (String[] args)
{
    int n,m,k;
    System.out.println("The number of lines of the first matrix is");
    n = sc.nextInt();
    System.out.println("The number of rows of the first matrix and the number of lines of the second matrix is ");
    m = sc.nextInt();
    System.out.println("The number of rows of the second matrix is ");
    k = sc.nextInt();

    double a[][] = new double[n][m];
    double b[][] = new double[m][k];
    double c[][] = new double[n][k];        

    read(a, n, m);
    read(b, m, k);

    multiply(a,b,c,n,m,k);

    write(c,n,k);
}

public static void read (double v[][], int q, int r)
{
    System.out.printf("\nThe numbers for the matrix are \n ");
    int i,j;
    for(i=0;i<q;i++)
    for(j=0;j<r;j++)
    {
        System.out.printf(" On the position %d %d%n ", i, j);
        v[i][j] = sc.nextDouble();
    }
}

public static void multiply (double v[][], double w[][], double u[][], int q, int r, int z)
{
    int i, j, t;
    for(i=0;i<q;i++)
    for(j=0;j<r;j++)
    {

        for(t=0;t<z;t++)
        u[i][t] = u[i][t] + v[i][t]*w[t][j]; 
    }

}

public static void write (double v[][], int q, int r)
{
    int i,j;
    for(i=0;i<q;i++)
    for(j=0;j<r;j++)
    {
        System.out.printf("c[%d][%d]= %f%n", i, j, v[i][j]);
    }
}

}

u[i][t] = u[i][t] + v[i][j]*w[j][t] 似乎对我有用。

您为数组输入了错误的数字。 v 由前两个数字声明,因此仅由 i 和 j 定义。 w 由后两个定义,因此由 j 和 t 声明。此外,这总是将 i 和 t 定义您要进入的矩阵槽的数字加在一起,并且两个矩阵中的 j 相同。

编辑:代码的第一行是放入 public static void multiply 的行。