[英]What if the declared variable in for each loop will print outside of the foor loop
我尝试为每个循环在数组中查找重复项,如果我在每个循环的外部打印变量“ i”,则会提供意外的输出。
预期:相关错误,例如未声明变量(因为声明的变量是局部变量)
package Login;
public class DupsArray {
public static void main(String[] args) {
int[] a = {1, 2, 3, 3};
int length = a.length;
for (int i : a) {
for (int j = i + 1; j <= length - 1; j++) {
if (a[i] == a[j]) {
System.out.println("Found duplicate" + a[i]);
break;
}
System.out.print(i);
}
}
}
}
11找到重复项3
您正在使用i
来迭代数组a
的值 (而不是索引),而使用j
来迭代index 。
建议:可以使用ArrayList
而不是使用数组,并使您的代码更简单:
迭代列表,对于任何item
将array.indexOf(item)
与array.lastIndexOf(item)
-如果它们不同,则会发现重复项!
我认为您应该在没有增强的for
循环的情况下执行此操作,因为需要索引比较以避免误报,例如,将元素i == 3
与元素a[j] == 3
,这可能是相同的,但是该怎么做您要确定吗? 为了解决这个问题,您将需要一个indexOf
,因此它将归结为再次进行索引比较。
我将对-loops使用两个经典方法for
并比较索引,跳过相等的索引:
public static void main(String args[]) throws Exception {
// the source to be investigated
int[] a = {1, 2, 3, 3};
// a container for duplicates found
Set<Integer> dups = new HashSet<>();
// iterate your elements of the source array
for (int i = 0; i < a.length; i++) {
// compare each one to the others
for (int j = i + 1; j < a.length; j++) {
// find out if the elements are equal
if (a[i] == a[j]) {
// if they are, add it to the set of duplicates
dups.add(a[i]);
// as an alternative, you could print them here, too
// System.out.println("Duplicate found: " + a[i]);
}
}
}
// print the duplicates found
System.out.println("Duplicates found: ");
dups.forEach(d -> System.out.println(d));
}
请阅读代码注释,并注意,如果只想打印副本,则不必存储副本。 需要存储以进行进一步处理或稍后再打印(可能是根据需要)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.