Shan Shan - 23 days ago 7
Java Question

Find duplicate values in an array in java

I am trying to write a code which will find the duplicate value in an array. So, far I have written below code:

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]);

}

}


}

}


But I am not getting the expected output, for example:


  1. If I give value 1,2,1,4,3,1 then it is successfully finding the duplicate value 1.

  2. But if I provide 2 set of duplicate value in an array, still it is finding the first duplicate.
    e.g. 1,2,1,2,1,3. It is giving output only 1.



I found the reason of incorrect result which is condition of count i.e. count is set to greater than 1 and it is not matching to first if condition.

So, I have tried to reset the counter to 0 after one loop iteration, now it is giving all duplicate values but duplicate values printing twice.

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;**

}

}


e.g. Input: 1,2,1,2,1,2, Output: 1 2 1 2

Please suggest how to get the correct result.

Answer Source

You are in the right way, I have just updated your method, I hope that you will understand what was your mistake:

public void findDupicateInArray(int[] a) {
        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]) {
                    count++;
                }
            }
            if(count==1)
               System.out.println(a[j]);
            count = 0;
        }
    }

Nevertheless, this will make your code running correctly, and that does not mean you have written the optimal code.