我有这个方法需要两个二维数组的实例将它们加在一起并将和存储在一个新数组中,这两个数组必须具有相同的大小,例如(相同的行数和列数),否则它将引发异常我定义的我的方法仅在第一个数组具有不同的行数而不是列数时抛出异常,例如,仅当我通过以下数组时才抛出异常:a [4] [4] b [5] [4]但不是这些数组:a [4] [5] b [4] [5],有人可以解释什么吗?我以正确的方式抛出异常吗?
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;
}
这就是调用方法的方式:
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);
}
最佳答案
您的支票有误。您应该在顶部执行的操作:
if (a.length != b.length || a[0].length != b[0].length) {
throw new IncompatibleArgumentsException(...);
}