Home  >  Article  >  Java  >  Why does my Java random number generator return the same number when called from another class?

Why does my Java random number generator return the same number when called from another class?

DDD
DDDOriginal
2024-11-07 04:54:02880browse

Why does my Java random number generator return the same number when called from another class?

Java Random Number Generator with Fixed Seed

Question:

In Java, when setting a seed for a random number generator, why does it always return the same number when I call the method from another class?

Code:

public class Numbers {
    public int random(int i) {
        Random randnum = new Random();
        randnum.setSeed(123456789);
        return randnum.nextInt(i);
    }
}

When calling numbers.random(10) multiple times, it consistently outputs the same value. How can we modify the code to generate different random numbers while maintaining the requirement to set the seed?

Answer:

To ensure that different random numbers are generated, the Random instance must be shared across the entire class rather than being recreated for each method call. This can be achieved through the following modifications:

public class Numbers {
    private Random randnum;  // Declare the Random instance as a class variable

    public Numbers() {
        randnum = new Random();
        randnum.setSeed(123456789);
    }

    public int random(int i) {
        return randnum.nextInt(i);
    }
}

By initializing the randnum instance in the class constructor and making it accessible through the class's methods, we ensure that the same Random object is used throughout the class, leading to different random numbers being generated with each method call.

The above is the detailed content of Why does my Java random number generator return the same number when called from another class?. 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