我正在尝试编写一个代码来查找数组中的重复值。所以,到目前为止,我已经写了下面的代码:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
//System.out.println("Please enter the length of Array: ");
int[] array = new int[6];
for(int i =0; i<array.length;i++) {
System.out.println("Enter value for index "+i+":");
array[i] = sc.nextInt();
}
FindDuplicateInArray obj = new FindDuplicateInArray();
obj.findDupicateInArray(array);
}
public void findDupicateInArray(int[] a) {
//int pointer = a[0];
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k] && j!=k && j<k && count<=1) {
count++;
if(count==1)
System.out.println(a[j]);
}
}
}
}
但是我没有得到预期的输出,例如:
如果我给出值 1,2,1,4,3,1 那么它就成功地找到了重复值 1。
但是,如果我在数组中提供 2 组重复值,它仍然会找到第一个重复值。例如 1,2,1,2,1,3。它只给出输出 1。
我发现结果不正确的原因是计数条件,即计数设置为大于 1,并且它与第一个 if 条件不匹配。
因此,我尝试在一次循环迭代后将计数器重置为 0,现在它给出所有重复值,但重复值打印两次。
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
//System.out.println("Please enter the length of Array: ");
int[] array = new int[6];
for(int i =0; i<array.length;i++) {
System.out.println("Enter value for index "+i+":");
array[i] = sc.nextInt();
}
FindDuplicateInArray obj = new FindDuplicateInArray();
obj.findDupicateInArray(array);
}
public void findDupicateInArray(int[] a) {
//int pointer = a[0];
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k] && j!=k && j<k && count<=1) {
count++;
if(count==1)
System.out.println(a[j]);
}
}
**count = 0;**
}
}
例如输入:1,2,1,2,1,2,输出:1 2 1 2
请建议如何获得正确的结果。
原文由 Shan 发布,翻译遵循 CC BY-SA 4.0 许可协议
你是对的,我刚刚更新了你的方法,我希望你能明白你的错误是什么:
尽管如此,这将使您的代码正确运行,但这并不意味着您已经编写了最佳代码。