Eliminating Duplicates in an Array
Write a method to eliminate the duplicate values in the array using the following method header:
public static int[] eliminateDuplicate(int[] numbers)
Write a test program that reads in ten integers, invokes the method, and displays the result. Here is the sample run of the program:
Quote:
Enter ten numbers: 1 2 3 2 1 6 3 4 5 2
The distinct numbers are: 1 2 3 6 4 5
Here is my code:
Code :
import java.util.*;
public class EliminatingDuplicates {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter ten numbers: ");
int[] numbers = new int[10];
for(int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
}
System.out.println("The distinct numbers are: ");
eliminateDuplicates(numbers);
}
public static void eliminateDuplicates(int[] numbers) {
for(int i = 0; i < numbers.length; i++) {
boolean distinct = true;
for(int j = 0; j < i; j++) {
if (numbers[i] == numbers[j]) {
distinct = false;
break;
}
if (distinct)
System.out.println(numbers[i]);
}
}
}
}
My code compiles. However when I run the program, no distinct numbers show up. This is my output.
Quote:
Enter ten numbers: 1 2 3 2 1 6 3 4 5 2
The distinct numbers are:
What am I doing wrong??
Re: Eliminating Duplicates in an Array
I think the problem is here:
Code :
for(int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
}
I'm guessing you're trying to fill the array "numbers" with the numbers you input... But instead you used this "int num", you probably meant putting
Code :
numbers[i] = input.nextInt();
Re: Eliminating Duplicates in an Array
Thanks, I fixed up that part of the code. I am able to get numbers to show up after "The distinct numbers are:". However they are not correct. I think there may be something wrong with my eliminateDuplicates method but I'm not sure what it is.
Re: Eliminating Duplicates in an Array
There is another much simpler way:
- Iterate over the list, adding each item to a Set.
- Since Set does not allow duplicate items, so the result is a set of unique items.
java exception
Re: Eliminating Duplicates in an Array
hi,
I am also agree that Set should be used for this what duplicate you do not want just use set of that object.
bean factory