Home > Java > javaTutorial > 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
Release: 2024-11-07 04:54:02
Original
965 people have browsed it

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);
    }
}
Copy after login

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);
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template