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?
If matrixes are empty, the statement
will throw an OutOfBoundsException because the position 0 of the matrix A is invalid.
Does two checks: