I am attempting to write a program, that consists of an array, filled with 50 random numbers, between the values 1-999. However before a random number is added to the array, I must check that the number is not a duplicate and not already in the array.
I seem to be fairly close to the correct output, however for some reason, i repeatedly get the number 0 as the first element in my array, and it is also the only number that is ever duplicated. Does anyone know why this is, and if so be able to provide a suitable fix?
Once a duplicate is found, it needs to be printed to the output, and replaced by a new unique random number.
Thanks in advance.
import java.util.*;
public class Random50 {
public static void main (String[] args)
{
final int MAX_SIZE = 50;
int[] r50 = new int[MAX_SIZE];
boolean duplicates = false;
Random rand = new Random();
for (int i=0; i<r50.length; i++)
{
for (int j=i+1;j<r50.length;j++)
{
r50[i] = rand.nextInt(1000);
if (j!=i && r50[i] == r50[j])
{
duplicates = true;
System.out.println("DUPE: " + r50[i]);
r50[i] = rand.nextInt(1000);
}
}
}
System.out.println(Arrays.toString(r50));
}
}
duplicatesafter you find a duplicateCollectionobjects have a.contains()method.Set<Integer>if you need to keep non-duplicate items. Your code could then be quite simple - loop, adding values to your set until it has 50 elements.Setmight be the best choice but to comment on your code afterif (j!=i && r50[i] == r50[j])is not guaranteed to get a non-duplicate number. Use awhilefor this.