首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java矩阵乘法ArrayIndexOutOfBounds异常

Java矩阵乘法ArrayIndexOutOfBounds异常
EN

Stack Overflow用户
提问于 2015-02-17 18:28:49
回答 1查看 776关注 0票数 1

我刚开始自己学习Java,我正在尝试做不同的程序,从C++到Java。我想用一些无效的方法来做矩阵的乘法,但是当我试图乘2-2 - 2-1,3-2 - 2-3,3-2-3,4-4 -4等矩阵时,我经常会得到这个例外(java.lang.ArrayIndexOutOfBoundsException)。这个程序适用于3-3-3-3,4-4-4等矩阵,但是当变量不一样时,它就失败了。我不明白我是怎么搞错的,有人能帮上忙吗?

Ty

导入java.util.Scanner;公共类MultiplicationOfMatrixes {

代码语言:javascript
复制
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]);
    }
}

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-17 18:51:55

ui = ui + vi*wj似乎在为我工作。

你为数组输入了错误的数字。V由前两个数字声明,因此只由i和j定义,w由第二个数定义,因此由j和t声明。此外,这总是将i和t定义到矩阵槽的数字相加,并且j在两个矩阵中都是相同的。

编辑:代码的最上面一行是被放入公共静态、无效、乘法的行。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28568540

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档