I want to generate random numbers in java, I know I should use existing methods like Math.random(), however, my question is: how can I generate the same sequence of numbers,
Sure - just create an instance of Random instead of using Math.random()
, and always specify the same seed:
Random random = new Random(10000); // Or whatever seed - maybe configurable
int diceRoll = random.nextInt(6) + 1; // etc
Note that it becomes harder if your application has multiple threads involved, as the timing becomes less predictable.
This takes advantage of Random
being a pseudo-random number generator - in other words, each time you ask it for a new result, it manipulates internal state to give you a random-looking sequence, but knowing the seed (or indeed the current internal state) it's entirely predictable.