2012-10-06 69 views
0

我不得不爲學校編寫這個程序,乘以一對二維數組。當我嘗試運行程序時,我總是遇到越界:3錯誤。Java二維數組乘法錯誤?

我已經翻遍了很多次的代碼,不能爲我的生活找出故障發生的地方。我運行了一個調試,第一個斷點在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(); 
    } 

} 

回答

1

您已經 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(); 
    } 
+0

非常感謝!我剛剛開始學習Java,這是我的一個完全疏忽。我覺得我還在摸索基本的扭結:-) – Erunamo114

0

如果將此for(int k = 0; k < a[0].length;)更改爲,程序將正確執行你錯過了k++裏面for循環。

+0

非常感謝!我剛剛開始學習Java,這是我的一個完全疏忽。我想我仍然在研究基本的問題:-) – Erunamo114

+0

歡迎您,也接受答案,如果這一個或其他真的是你的問題的答案。 – Abubakkar