I am trying to write a code that would find duplicate values and this is my code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
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 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]);
}
}
}
}
By using the above code, I am not getting the expected output, for example:
If I give value 1,2,1,4,3,1 then it is successfully finding the duplicate value 1.
But if I provide 2 set of duplicate values 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 have again written the code making some changes:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
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 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;**
}
now the new one is giving all duplicate values but duplicate values printing twice. e.g. Input: 1,2,1,2,1,2, Output: 1 2 1 2.
Please suggest how to do this correctly.