Java 矩阵乘法 ArrayIndexOutOfBounds 异常

标签 java matrix indexoutofboundsexception multiplication

我刚刚开始自己​​学习 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)类乘法矩阵{

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 的行。

关于Java 矩阵乘法 ArrayIndexOutOfBounds 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28568540/

相关文章:

c# - 使用参数创建新线程时索引超出范围?

c++ - 对称矩阵,值转换为 C++ vector

java - 如何使用jackson将xml解析为json

java - Amazon CLI 并行部署

java - 为什么这个 ID 选择在 Jsoup 中不起作用?

c++ - 列出矩阵类的初始化

matlab - 按第一列索引对不同行中的值进行分组

java - ArrayAdapter - 如何停止 getView 调用?

java - Hibernate获取SQL query.list() : ArrayIndexOutOfBoundsException 0

java - Docker 服务健康检查不适用于 Spring Boot 应用程序