11

In my code I use random numbers in different classes. How to define random seed? Can I define this seed for all the classes in the main code?

double rnd = Math.random();
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217

2 Answers2

27

You will probably want to use the special Random class. It gives you more control over the random numbers. To do this you first need to create a new random object.

Random generator = new Random(seed);

Then generate a new number by

double random = generator.nextDouble();

http://docs.oracle.com/javase/6/docs/api/java/util/Random.html

David Conrad
  • 15,432
  • 2
  • 42
  • 54
Thijser
  • 2,625
  • 1
  • 36
  • 71
0
public class MathRandomWithSeed {

    public static void main (String args[]){

        int min = 5;
        int max = 100;
        int seed = 5;
        
        int random = randomNext(min, max, seed);

        System.out.println("Random = " + random);
    }

    private static int randomNext(int min, int max, int seed){

        int count = (max - min) / seed;

        int random = ((int)(count * Math.random()) * seed) + min;

        return random;
    }
}
Gurm
  • 1