Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java random always returns the same number when I set the seed?

Tags:

java

random

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

like image 948
badcoder Avatar asked Apr 03 '11 23:04

badcoder


People also ask

How does Java random work with seed?

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random .

How do you generate a random number from a seed in Java?

There are two ways we can generate random number using seed. Random random = new Random(long seed); Random random1 = new Random(); random1. setSeed(seed); The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method next(int).

What does random seed return?

A random seed is a starting point in generating random numbers. A random seed specifies the start point when a computer generates a random number sequence. This can be any number, but it usually comes from seconds on a computer system's clock (Henkemans & Lee, 2001).


1 Answers

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);     } } 
like image 62
Sophie Alpert Avatar answered Oct 14 '22 15:10

Sophie Alpert