Home >Java >javaTutorial >Why Does My Java Random Number Generator Always Return the Same Number Despite Setting a Seed?
Java Random Number Generator Always Returns Same Number Despite Seed
In the provided Java code, despite setting a seed, the random number generator consistently yields the same number. The issue arises when creating a new Random object for each method call. This ensures that a new seed is generated each time, resulting in the repetition of random numbers.
To resolve this, it is essential to share a single Random instance across the entire class. By incorporating this change, we guarantee that the seed is set just once, leading to a sequence of genuinely random numbers.
public class Numbers { // Shared Random instance private Random randnum = new Random(); public int random(int i) { randnum.setSeed(123456789); return randnum.nextInt(i); } }
With this modification, subsequent calls to the random method will return different numbers, adhering to the constraints of having a fixed seed.
The above is the detailed content of Why Does My Java Random Number Generator Always Return the Same Number Despite Setting a Seed?. For more information, please follow other related articles on the PHP Chinese website!