【发布时间】:2021-08-08 04:58:44
【问题描述】:
我的程序有一个布尔数组,它在比较两个数组之间的元素时返回 true,即使它们的值不相等。如何将我的 compArray 方法更正为仅在元素彼此相等时才返回 true 的位置?
public static boolean compArray(double[] a, double[] b, int n) {
for (int i = 0; i < a.length; i++) {
if (a.length == b.length) {
if (a[i] == b[i]) {
return true;
} else return false;
}
}
return false;
}
public static void main(String[] args) {
double[] a = new double[5];
double[] b = new double[5];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of values: ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("Please enter values for array a: ");
a[i] = sc.nextDouble();
System.out.println("Please enter values for array b: ");
b[i] = sc.nextDouble();
}
boolean match = compArray(a, b, n);
for (int i = 0; i < n; i++) {
if (compArray(a, b, n)) {
System.out.println("A " + a[i] + " B " + b[i] + " true");
System.out.println();
} else {
System.out.println("A " + a[i] + " B " + b[i] + " false");
System.out.println();
}
}
sc.close();
}
【问题讨论】:
-
现在,由于您在
for循环内有一个return语句,所以return第一次执行时,整个函数将结束。这意味着如果数组中的第一个元素相等,该函数将立即返回true。