I am try to remove duplicates from an array that entered by the user, by using loop and scanner only. I am trying without using any library methods, when I enter an array = {1 , 2 , 1}; the program print 1 three times.
import java.util.*;
public class Duplicates {
public static void main(String []args) {
Scanner kb = new Scanner(System.in);
// The size
System.out.print("Enter the size of the array: ");
int n = kb.nextInt();
// the elements
System.out.printf("Enter %d elements in the array: ", n);
int [] a = new int[n];
for(int i = 0; i < a.length; i++)
a[i] = kb.nextInt();
// remove duplicate elements
for(int i = 0; i < a.length; i++){
for(int j = i+1; j < a.length; j++){
if (a[j] != a[i]){
a[j] = a[i];
++j;
}
a[j] = a[i];
}
}
// print
for(int k = 0; k < a.length; k++)
System.out.print(a[k] + " ");
}
}
thank you,