Are Java random numbers random?

I tried to tell a random number generator in Java to a friend as he continued to get the same numbers every time the program started. I created my own simpler version of the same, and I also get the exact exact numbers that he got every time I run the program.

What am I doing wrong?

import java.util.*; public class TestCode{ public static void main(String[] args){ int sum = 0; Random rand = new Random(100); for(int x = 0; x < 100; x++){ int num = (rand.nextInt(100)) + 1; sum += num; System.out.println("Random number:" + num); } //value never changes with repeated program executions. System.out.println("Sum: " + sum); } } 

The last five numbers out of 100:

 40 60 27 56 53 
+7
source share
4 answers

You have chosen a random generator with a constant value of 100 . It is deterministic, so it will generate the same values ​​that are executed every time.

I'm not sure why you selected it with 100 , but the initial value has nothing to do with the range of generated values ​​(which is controlled by other means, such as calling nextInt that you already have).

To get different values ​​each time, use the Random constructor without arguments, which uses the system time to generate a random generator.

Quote from Javadoc for the carefree constructor Random :

Creates a new random number generator. This constructor sets the seed of a random number generator to a value that is likely to be different from any other call to this constructor.

Quoting the actual code in a constructor without Random parameters:

 public Random() { this(seedUniquifier() ^ System.nanoTime()); } 
+23
source

It:

  Random rand = new Random(100); 

You give the random number generator the same seed (100) every time you run the program. Give it something like the output from System.currentTimeMillis() , and this should give you different numbers for each call.

+2
source

Random number generators are really only pseudo-random. That is, they use deterministic tools to generate sequences that seem random under certain statistical criteria.

The constant constant Random(long seed) allows you to pass a seed that defines a sequence of pseudorandom numbers.

+1
source

Hope this helps.

 Random r = new Random(System.currentTimeMillis()); double[] rand = new double[500]; for(int i=0;i<100;i++){ rand[i] = r.nextDouble(); //System.out.print(rand[i] + "\n"); } //System.out.println(); return rand[randomInt]; 
0
source

All Articles