I am trying to generate a 5 digit int
array in Java and am having trouble on where to start. None of the numbers in the array can be duplicates. I can generate random numbers for it fine but just cant figure out how to compare the numbers to each other and replace any duplicates.
You can use a java.util.Set instead of an array as it is guaranteed to have only unique elements.
If I understand you correctly, you want a random 5 digit number, with no digit repeated?
If so, one way is to shuffle a list of the digits 0-9, then pick the first 5 elements.
EDIT
Integer[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Random random = new Random();
public Integer[] generateId() {
List<Integer> id = Arrays.asList(digits);
Collections.shuffle(id, random);
return id.subList(0, 5).toArray(new Integer[0]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With