0

エラーメッセージは - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 です

2D 配列をメソッドに渡し、配列内の値を 2 で乗算しています。以下のメソッドを次に示します。

main から最初の配列を渡しても 2 番目の配列を渡さない場合は正しく動作します。これらはメソッド コードの下にも示されています。

このエラーを修正する方法を知っている人はいますか? また、ループの繰り返しなどをハードコーディングすることもできません

int setuparray2 [][] = new int [][] {{4, 5},{6, 9} };                               
int setuparray3 [][] = new int [][] {{4, 6, 3},{-1,9,-5}};

scalarMultiplication(2,setuparray1);
scalarMultiplication(2,setuparray3);


public static void scalarMultiplication( int factor, int[][] a)
{   
    //creates a new array to hold the multiplied value
  int multiplyArray [][] = new int [a.length][a.length];

  for(int i = 0; i < a.length; i++)
  {
    for(int j = 0; j < a[i].length; j++)
    {   
    //multiplys each element in the array by the factor     
    multiplyArray[i][j] = a[i][j] * factor;                                     
    }
  }
  //prints the array with the results
  printArray(multiplyArray);
}
4

2 に答える 2

1

作成時にmultiplyArray十分なスペースを確保していません。

それ以外の:

int multiplyArray [][] = new int [a.length][a.length];

書く:

int multiplyArray [][] = new int [a.length][a[0].length];
于 2013-03-03T15:57:30.660 に答える
0

あなたはそれを間違った方法で初期化しています、以下は正しい方法であるはずです

 int multiplyArray [][] = new int [2][3];
于 2013-03-03T16:00:32.493 に答える