[英]Comparing elements of two arrays
我的方法接受两个整数 arrays 并返回true
如果
它适用于我的所有测试用例,除了int[] a = {1, 2, 3}
和int[] b = {4, 5, 1}
。 即使a[2] > b[2]
,它也会返回 true 。 digitDifference
检查无法正常工作,但我看不到错误。
public static boolean allLess(int[] a, int[] b) {
int i = 0;
boolean sameLength = (a.length == b.length);
boolean digitDifference = (a[i] < b[i]);
for (i = 0; i <= a.length - 1; i++) {}
return (sameLength && digitDifference);
}
您的方法仅比较每个数组中的第一个元素-比较是在for
循环(空!)之外而不是在其中进行的。 将其移到那里,您应该可以。
值得注意的是,在这种情况下,使用早期返回成语将有助于产生更易于阅读的代码,因为您无需继续与自己“拖动”当前状态,只需在其中一个条件被破坏时快速进行故障转移:
public static boolean allLess(int[] a, int[] b) {
if (a.length != b.length) {
return false;
}
for (i = 0; i <= a.length - 1; i++) {
if (a[i] >= b[i]) {
return false;
}
}
return true;
}
您的for
循环不执行任何操作,因此您仅比较数组的第一个索引中的元素。
您的代码应如下所示:
public static boolean allLess(int[] a, int[] b) {
boolean sameLength = (a.length == b.length);
if (!sameLength)
return false;
boolean digitDifference = true;
for (int i = 0; i <= a.length - 1 && digitDifference; i++) {
digitDifference = (a[i] < b[i]);
}
return digitDifference;
}
现在,for循环比较具有相同索引的每对元素,并在发现违反您的要求(a[i] < b[i])
一对元素时终止。
另一个没有标志的等效实现:
public static boolean allLess(int[] a, int[] b) {
if (a.length != b.length)
return false;
for (int i = 0; i <= a.length - 1; i++) {
if (a[i] >= b[i])
return false;
}
return true;
}
在循环之前初始化digitDifference
,并比较两个数组的第一个元素,因为此时i
的值为0。 您永远不会比较数组的其他元素。 比较必须在循环内完成。
顺便说一句,您的循环主体甚至没有一条指令。
您可以检查比较两个数组的长度,但是只能在方法末尾对其进行操作。 Java和其他任何语言一样,允许您在一个方法中使用多个return语句,因此我的建议是在执行检查后立即从该方法返回:
if (a.length != b.length)
return false;
其次,代码中的digitDifference
语句仅对数组中的第一个元素进行一次评估。 我相信,您希望for循环在数组中的每个元素上执行多次比较,但是,您将循环主体留为空白。
for (i = 0; i <= a.length - 1; i++) {
if(a[i] >= b[i])
return false;
}
再一次,我的建议是,一旦发现其中一个因素违反了您的约束,就应立即返回。 并且只有一个return true;
的return true;
在for循环之后,这将指示所有元素均满足约束a[i] >= b[i]
。
List<String> list1 = List.of("Banana", "Watermelon", "Carrot");
List<String> list2 = List.of("Apple", "Plum", "Orange");
System.out.println(list1.stream().anyMatch(list2::contains));
Output:假
List<String> list1 = List.of("Banana", "Watermelon", "Carrot");
List<String> list2 = List.of("Apple", "Plum", "Orange", "Watermelon");
System.out.println(list1.stream().anyMatch(list2::contains));
Output:真
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.