I am trying to generate 5 different random numbers for use in my card game app, so far i am using a while loop as follows which prints out 5 of the same number, i am wondering how to make 5 DIFFERENT random numbers, surely it cant be much different to the code i have so far….
int n = 0;
while(n<5)
{
Random r = new Random();
int i = r.nextInt(10);
System.out.println( i);
n++;
}
I hope somebody can help 🙂
x
Try moving
Random r = new Random();outside of your while loop.The seed is based on the timestamp:
(reference)
Since you’re not doing much inside your loop it’s not taking more than a millisecond between calls, which means that each
new Random()is initialized with the same seed.