I require help with a random number generator I am creating. My code is as follows (inside a class called numbers):
public int random(int i){
Random randnum = new Random();
randnum.setSeed(123456789);
return randnum.nextInt(i);
}
When I call this method from another class (in order to generate a random number), it always returns the same number. For example if I were to do:
System.out.println(numbers.random(10));
System.out.print(numbers.random(10));
it always prints the same number e.g. 5 5. What do I have to do so that it prints two different numbers e.g. 5 8
It is mandatory that I set the seed.
Thanks
You need to share the Random()
instance across the whole class:
public class Numbers {
Random randnum;
public Numbers() {
randnum = new Random();
randnum.setSeed(123456789);
}
public int random(int i){
return randnum.nextInt(i);
}
}