I want to find out the duplicate element and there index number from an array. I write down a code for that. It works well but only fail to generate exact output when number of duplicate element more than 2. I read the value from a file and then build an array and then searching duplicate element from this array.
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class T1 {
public static void main(String args[]) throws Exception{
Scanner x=new Scanner(new File("C:\\Duplicate_array.txt"));
int [] duplicate_data=new int[9];
int i1=0;
while(x.hasNext()){
int a=x.nextInt();
duplicate_data[i1]=a;
i1++;
}
System.out.println(Arrays.toString(duplicate_data));
for (int i = 0; i < duplicate_data.length-1; i++) {
for (int j = i+1; j < duplicate_data.length; j++) {
if ((duplicate_data[i] == duplicate_data[j]) && (i != j)) {
System.out.println("Duplicate Element : "+duplicate_data[j]);
System.out.println("Index of that duplicate element : "+j);
}
}
}
}
}
Here is my output:
[5, 6, 1, 6, 9, 5, 2, 1, 5]
Duplicate Element : 5
Index of that duplicate element : 5
Duplicate Element : 5
Index of that duplicate element : 8
Duplicate Element : 6
Index of that duplicate element : 3
Duplicate Element : 1
Index of that duplicate element : 7
Duplicate Element : 5
Index of that duplicate element : 8
Error at last line.It already find 5 at the beginning at position no: 8. But at the end of the program it again searching for 5 and give the position no. This last search is unnecessary. How to get rid of this last search?