1

I'm just writing a short piece of code for adding matrices. So far the method I have written is:

public static int[][] matrixAdd(int[][] A, int[][] B)
{
   int[][]C = new int[A.length][A[0].length];

   for(int i =0; i < A.length; i++)
  {
  for(int j=0; j < A[i].length;j++)
  {
     C[i][j] = A[i][j] + B[i][j]; 
  }
}


return C;
}

This code does add matrices correctly, however I get an index out of bounds exception if the matrices passed to this method are empty. The error apparantly relates to the line in which the size of 'C' is delared. What is wrong with my logic?

user650309
  • 2,639
  • 7
  • 28
  • 47
  • 2
    Are you sure A and B have the same dimensions? Maybe you should validate that too. – Marcelo May 19 '11 at 23:07
  • 1
    This is a great opportunity to start learning how to use a debugger. Try setting a breakpoint at the `int C[][]` line, and inspect the various values when the AIOOBE is thrown. – Matt Ball May 19 '11 at 23:08

2 Answers2

1

Assuming that both A and B are square matrix with equal dimensions, I think it would fail in A[0].length since you are not checking for bounds (i.e. emptiness).

One thing to bear in mind is that higher dimensional arrays in Java are nothing but array of arrays, hence it should treated as is.

kuriouscoder
  • 5,394
  • 7
  • 26
  • 40
0

If matrixes are empty, the statement

 int[][]C = new int[A.length][A[0].length];

will throw an OutOfBoundsException because the position 0 of the matrix A is invalid.

Does two checks:

 if ((A.length < 0) || (A[0].length < 0)) return B;
 if ((B.length < 0) || (B[0].length < 0)) return A;
Pih
  • 2,282
  • 15
  • 20