I want to generate random numbers between two integer numbers. In my case the numbers must meet some other conditions. I put generator.nextInt(x)
in a loop and set seed again, if the new number doesn't meet my conditions.
The number which is generated is same in the number of loop iteration when I use System.currentTimeMillis()
as seed. I replace System.currentTimeMillis()
with System.nanoTime()
. the result much better than previous one.
I want to know is there any better way for setting the seed?
If you repeatedly use System.currentTimeMillis() it won't actually be changing that often. i.e. once per milli-second at best. If you use System.nanoTime() it can change every micro-second or better.
I suspect you don't need to reset the seed as the sequence is supposed to be random. Just keep picking random numbers instead.
You don't need to seed again. Everytime you do the
generator.nexInt(x)
you get a new random number, that is0 <= random_number < x.
You can use the constructor for
Random
that doesn't take a parameter. That constructor initializes its seed based onSystem.nanoTime()
already. Every time you invoke that constructor the seed will be different.Generally you would only seed
Random
yourself when you want a repeatable sequence of random data (they are determinstic).Either way, you can always keep calling
nextInt
(or anynextXyz
method) and keep getting more random numbers without having to re-seed for every number.Random numbers in Java are pseudo-random. They need a seed that is used to generate the next random number.