Schming Schming - 1 year ago 65
Java Question

Random number generator giving inconsistent results

I am trying to work out how to add 6 randomly generated numbers to a HashSet. I am getting results but they are inconsistent. Sometimes it prints 6 numbers to the console and other times it prints 5 numbers to the console.

I'm new to this stuff only this morning so I apologize if it is blatantly obvious and thank you for your help.

HashSet<Integer> generatedLotteryNumbers = new HashSet<Integer>();
Random r = new Random();

for(int i=0; i<6; i++){


Answer Source

A Set cannot contain duplicate values, so if the generator produces the same number twice, it will be removed. Instead, you should loop based on the size of the Set (or use a List):

while (generatedLotteryNumbers.size() < 6) {

If you're using Java 8, another option is to use Random#ints to generate a Stream which you can use to directly create your Set.

Set<Integer> generatedLotteryNumbers = r.ints(0, 49)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download