Adding matrices Java
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.leng开发者_运维知识库th][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?
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.
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;
精彩评论