2D数组帮助 - 乘以负数

时间:2013-03-03 15:53:43

标签: java arrays loops

错误消息是 - 线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:2

我将2d数组传递给方法,并将数组内的值乘以2.这是下面的方法。

当我从main传入第一个数组而不是第二个数组时它正常工作 - 这些也显示在方法代码下面

有没有人知道如何修改此错误?我也不能硬编码循环迭代等

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);
}

2 个答案:

答案 0 :(得分:1)

创建multiplyArray时,您没有预留足够的空间。

而不是:

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

写:

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

答案 1 :(得分:0)

您正在以错误的方式初始化它,下面应该是正确的方法

 int multiplyArray [][] = new int [2][3];