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?

2
  • 2
    Are you sure A and B have the same dimensions? Maybe you should validate that too. Commented May 19, 2011 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. Commented May 19, 2011 at 23:08

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.