【发布时间】:2018-12-23 13:48:11
【问题描述】:
我正在编写一个带有 2 个参数、一个 int 矩阵和 1 个 int 数组的方法。该方法必须返回数组 b[] 中具有倍数的 a[][] 元素的总和。
这是方法代码
public static int sum(int[][] a, int[] b) {
int matrixSum = 0;
if (a != null && b != null) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
boolean multiple = false;
boolean nullRow = false;
if (a[i] == null || a[i].length < 1) {
nullRow= true;
} else {
for (int k = 0; k < b.length && !multiple; k++) {
if (b[k] % a[i][j] == 0) {
matrixSum += a[i][j];
multiple = true;
}
}
}
}
}
}
return matrixSum;
}
这是测试类
public static void main(String[] args) {
int[][] a = {{2, 3, 1}, {1, 1, 1}, {2, 2, 2}};
int[][] a1 = {{2, 3}, {1, 1, 1}, {2, 2, 2}};
int[][] a2 = {{2, 3, 4}, {1, 1}, {2, 2, 2}};
int[][] a3 = {{2, 3, 4}, {1, 2, 3}, {1, 1}};
int[] b = {7, 8, 7, 20};
System.out.println(sum(a, b)); // 15
System.out.println(sum(a1, b)); // 11
System.out.println(sum(a2, b)); // 14
System.out.println(sum(a3, b)); // 11
}
在某些情况下它可以在其他情况下不工作,有些结果不正确,而其他时候我收到 OutBound 错误
【问题讨论】:
-
在我们担心 Java 代码之前,让我们先试着把问题陈述下来。
having a multiple in the array这里到底是什么意思,能举个简单的3x3矩阵例子吗? -
你学会如何使用调试器了吗?
-
对于这个矩阵 int[][] a = {{2, 3, 1}, {1, 1, 1}, {2, 2, 2}} 和这个数组 int[] b = {7, 8, 7, 20} 倍数是 8 和 20,所以方法必须求和:2+1+1+1+1+2+2+2
-
sum : 2+1+1+1+1+2+2+2= 12,而不是 15。