Despite setting the seed of the Random class with a specific value, the random number generator is consistently returning the same number. Let's explore what could be causing this issue.
The Java Random class is designed to generate pseudo-random numbers. By default, it uses its internal clock as a seed value, causing it to generate a relatively predictable sequence of numbers. To customize the sequence, you can explicitly set a seed using the setSeed() method.
The seed is a numerical value used to initialize the internal state of the random number generator. This state determines the sequence of numbers generated.
In the provided code, you are creating a new instance of Random within the random() method. This means that every time you call random(), a new seed is being set, effectively overriding the previously set seed value.
To resolve this issue, you need to share the Random instance across the entire class. By creating a single instance and setting the seed once when the class is initialized, you ensure that the same sequence of numbers is generated consistently.
The following updated code solves the issue:
public class Numbers { private Random randnum; public Numbers() { randnum = new Random(); randnum.setSeed(123456789); } public int random(int i) { return randnum.nextInt(i); } }
In this updated code:
By making these changes, you will now obtain different random numbers when calling random() from different parts of your program, while still respecting the specified seed value.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3