I have this method which takes two instances of two dimensional arrays to add them together and store the sum in a new array, the two arrays must have the same size eg.(the same rows and columns number) if not it should throw an exception that I defined. my method is throwing the exception only if the first array has a different number of rows and not columns for example the exception is thrown only when I pass these arrays: a[4][4] b[5][4] but not these arrays: a[4][5] b[4][5], can someone explain whats happing? and I'm I throwing the exception the right way?
public int[][] add(int[][] a, int[][] b) throws IncompatibleArgumentsException {
int[][] sum = new int[a.length][b.length];
if (a.length == b.length) {
System.out.println("The Sum of the arrays is: ");
System.out.println(" --------------- ");
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < b.length; col++) {
sum[row][col] = a[row][col] + b[row][col];
System.out.println(" | " + a[row][col] + " + " + b[row][col] + " = " + sum[row][col] + " | ");
System.out.println(" --------------- ");
}
}
} else {
throw new IncompatibleArgumentsException("Arrays have different size");
}
return sum;
}
and this is how am calling the method:
public Implementation() {
int[][] x = new int[1][1];
x[0][0] = 1;
int[][] y = new int[1][2];
y[0][0] = 1;
y[0][1] = 3;
add(x, y);
}