Home >Java >javaTutorial >Why Does My Java Random Number Generator Always Return the Same Number Despite Setting a Seed?

Why Does My Java Random Number Generator Always Return the Same Number Despite Setting a Seed?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-07 07:11:02666browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Running Sum of ArrayNext article:Running Sum of Array