Reputation: 13
I am trying to remove duplicate numbers using method and return non-duplicate numbers, actually I am stuck in method right now. this is my code :
import javax.swing.JOptionPane;
public class duplicateRemover{
public static void main(String[] args) {
int[] array = new int[5];
for (int i=0; i<array.length;i++) {
String s=JOptionPane.showInputDialog(null,"PLEASE ENTER AN INTEGER:","INTEGERS",JOptionPane.QUESTION_MESSAGE);
array[i] = Integer.parseInt(s);
}
removeDuplicates(array);
for (int i=0; i<array.length;i++) {
JOptionPane.showMessageDialog(null,array[i],"UNIQE INTEGERS",JOptionPane.PLAIN_MESSAGE);
}
}
public static int[] removeDuplicates(int a []) {
int []removedDup=new int[a.length];
for (int i = 0; i < a.length; i++) {
for (int j = i-1; j < a.length; j++){
if (a[i] == a[i]) {
removedDup[i] = j;
break;
}
}
Upvotes: 0
Views: 1350
Reputation: 12744
This will do:
public static int[] removeDuplicates(int a[]) {
int n = a.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n;) {
if (a[j] == a[i]) {
for (int k = j; k < n-1; k++)
a[k] = a[k + 1];
n--;
} else
j++;
}
}
int[] newArray = new int[n];
System.arraycopy(a, 0, newArray, 0, n);
return newArray;
}
Upvotes: 0
Reputation: 6522
Do I understand right that you want to get all the integers that occur only once? This can be done easily with the collections API.
public static int[] removeDuplicates(int[] a) {
Set<Integer> unique = new TreeSet<Integer>();
List<Integer> results = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++) {
if (!unique.add(a[i]))
results.add(a[i]);
}
int[] ret = new int[results.size()];
for (int i = 0; i < results.size(); i++)
ret[i] = results.get(i);
return ret;
}
Upvotes: 1
Reputation: 976
Scan your array for each value and compare it with each other (you should have a nested "for"), then keep a list with duplicates' indexes, instantiate an array of size a.length-listOfDuplicateIndexes.size()......fill this array with a[] components whose indexes are not int ListOfDuplicateIndexes
Upvotes: 0
Reputation: 1434
obviously you're trying to multi loop element and compare it with others so if duplicate of that element exists you remove it and flag its index. this code you've written is buggy however I see your main problem now is that you compare element to it's very own
I see if (a[i] == a[i])
to be if (a[i] == a[j])
then your code supposed to work or throw index out of bound exception
Upvotes: 0