矩阵数学代码错误

时间:2018-04-10 10:45:28

标签: java arrays math

我正在尝试编写一个代码来执行矩阵乘法运算。现在,我非常希望以下人员可以胜任这项工作, - 根据blueJ,没有语法错误! - 但是当我尝试运行它时,它表示存在错误,如下所示:

import java.util.Scanner;
import java.util.Arrays;

public class matrix{

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("please enter n' of lines and columns in A");
        int linesA = scan.nextInt();
        int columnsA = scan.nextInt();
        System.out.println("please enter n' of lines and columns in B");
        int linesB = scan.nextInt();
        int columnsB = scan.nextInt();
        // NOW WE HAVE LINES & COLUMNS OF A AND B

        if (columnsA == linesB)
            System.out.println("please enter A, line by line");
        else
            System.out.println("please enter valid information");

        int Axx = columnsA * linesA; // now we have the number of degits in A
        int[] Aln = new int[Axx];// now we created the array that would hold A
        int i = 0;// only to count to input of all A
        while (i < Axx) {
            Aln[i] = scan.nextInt();// inputs of A
            i++;
        }// now we have all degits of A

        int Bxx = columnsB * linesB;
        int[] Bln = new int[Bxx];
        System.out.println("please enter B , line by line");
        i = 0;// only to count to input of all B
        while (i < Bxx) {
            Bln[i] = scan.nextInt();// inputs of B
            i++;
        }// now we have all degits of B
        int sizeTarget = linesA * columnsB;
        int[] target = new int[sizeTarget];
        i = 0;
        int a = 0;
        int b = 0;
        while (i < sizeTarget) {
            int sum = 0;
            while (i < columnsA) {
                sum += (Aln[a]) * (Bln[b]);
                a++;
                b += columnsB;
                target[i] = sum;
            }
            i++;
        }

        System.out.println(Arrays.toString(target));

    }
}

然后它说有一个&#34;越界数组索引&#34;在行

      sum+= (Aln[a])*(Bln[b]

1 个答案:

答案 0 :(得分:-1)

问题是在嵌套的while循环中,你只在外循环上增加i。在内循环中,“i”保持相同但“a”增量。所以你的内循环将继续保持运行,因为你只对“i”进行检查,你永远不会增加“i”。