簡體   English   中英

Java二維數組乘法錯誤?

[英]Java Two-Dimensional Array Multiplication Error?

我必須為學校編寫該程序,該程序將一對二維數組相乘。 當我嘗試運行程序時,我不斷出現出界錯誤:3錯誤。

我已經遍歷了很多遍代碼,無法終生確定發生故障的位置。 我運行了一個調試程序,第一個斷點在if語句“ if(a [0] .length!= b.length)”處,我不知道為什么這是斷點。

有人可以幫我嗎?

    public class Multiply {

    public static double[][] Multiply_2D_Arrays(double[][] a, double[][] b)

    { 
        if (a[0].length != b.length) // Check to see if the number of a's colums equals the number of b's rows
        {
            throw new IllegalArgumentException("Matrices don't match: " + a[0].length + " != " + b.length);

        }

        int a_rows = a.length;      // Defines the variable M as the row length of array a
        int b_columns = b[0].length;   // Defines the variable N as the column length of array b
        double[][] c = new double[a_rows][b_columns]; // This means that the dimensions of array c will be the rows of a by the columns of b

        for(int i = 0; i < a.length; i++)
            {
                for(int j = 0; j < b[0].length; j++)
                {
                    for(int k = 0; k < a[0].length; )
                    {

                        c[i][j] += a[i][k] * b[k][j];     //Iterates through each row and column of array a and b and then adding it to the dot point sum

                    }

                }
            }

            return c;      //returns the final new array c

        }

    public static void main(String[] args)

    {
        double[][] array1 = {{4.0, 5.0, 6.0}, {2.0, 1.0, 4.0}, {8.0, 7.0, 6.0}, {1.0, 1.0, 2.0}};
        double[][] array2 = {{5.0, 7.0, 7.0, 8.0}, {8.0, 8.0, 9.0, 2.0}, {10.0, 2.0, 3.0, 1.0}};
        double[][] array3 = Multiply.Multiply_2D_Arrays(array1, array2); //Calls the Multiply_2D_Arrays method

        for(int i = 0; i < array3.length; i++)
        {
            for (int j = 0; j < array3.length; j++)
            {
                System.out.print(array3[i][j] + " ");
            }
        }

        System.out.println();
    }

}

您錯過了for(int k = 0; k < a[0].length; ) k++

然后你有一個無限循環

另外,如果要將結果打印為矩陣,請將System.out.println()放入for循環中:

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

如果將for(int k = 0; k < a[0].length; )更改for(int k = 0; k < a[0].length;k++ ) ,則程序將正確執行,而您錯過了其中的k++ for循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM