# Removing duplicates from double Arrays

• 10-30-2010, 09:20 PM
jhong253
Removing duplicates from double Arrays
Hello,

I'm trying to write a program with a method that takes an array of various double type numbers of any size, then return only the unique numbers (return an array without the duplicates) while maintaining the order.

So input {5, 3, 5, 5, 3, 2, 1, 3, 4} should return {5, 3, 2, 1, 4}.

Here's the code:
Code:

public double[] uniqueNumbers(double[] Numbers) {
double[] u = new double[Numbers.length];
double num = Numbers[0];
u[0] = num;
int ii = 1;
for (int i = 0; i < u.length; i++){
if (Numbers[i] != num){
num = Numbers[i];
u[ii] = num;
ii++;
}
}
/*this is the part where I try to make an array u with only the duplicates, then leave the rest with 0s*/

double[] un;
int x = 0;
for (int z = 0; z < u.length; z++){
if (u[z] == 0){
x = z + 1;
}
}
un = new double[x];
for (int y = 0; y < u.length; y++){
if (u[y] != 0){
[B]un[y] = u[y];[/B] // this is where the error occurs apparently
}
}
return un;
/* here I tried to create a new array un that would have the values from u moved over except the 0s */

}

But when I run it I get this: :(

Quote:

java.lang.ArrayIndexOutOfBoundsException: 0
at xxxxxx.uniqueNumbers(xxxxxx.java:77)
Any idea why?

EDIT: Per Fubarable's suggestion, I put in a few println statements here and there, and the 1st part of the code where I create array u, it seems like the input array Numbers just gets copied over to u... :(
• 10-30-2010, 09:31 PM
Fubarable
What line in your code above causes this error to occur? Have you added println statements to see the state of your variables at the time or just before the error occurs?
• 10-30-2010, 10:07 PM
jhong253

I'm going to edit the original post to reflect on what's where... one sec.
• 10-30-2010, 10:32 PM
joshdgreen
If I'm not mistaken:

Code:

double[] un;
int x = 0;
for (int z = 0; z < u.length; z++){
if (u[z] == 0){
x = z + 1;
}
}
un = new double[x];

What if "u" has 25 values and number [3] and [24] had zeros. "X" would then be equal to... I'm not sure I really understand the use of this statement and then using "X" to declare the size of your next array?