Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I obtain the same number with Random Run?

Tags:

java

random

math

I am following a book and in this code:

    Random rand = new Random(47);
    int i, j, k;
    j = rand.nextInt(100) + 1;
    System.out.println("j : " + j);
    k = rand.nextInt(100) + 1;
    System.out.println("k : " + k);

I have the same number in output of the book, that is:

j : 59
k : 56

If I use

Random rand = new Random();

without 47 Random Class produces random number and it's ok, but why if I put inside the number 47 joined with j = rand.nextInt(100) + 1; Why I obtain the same output of the book? Thank you

like image 852
Lost_in_the_code Avatar asked Dec 18 '25 13:12

Lost_in_the_code


1 Answers

From the documentation:

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.

You can specify the seed in the constructor

Creates a new random number generator using a single long seed.

See also:
Pseudorandom number generator - Wikipedia

like image 132
Arc676 Avatar answered Dec 21 '25 15:12

Arc676



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!