jeudi 17 juin 2021

Random nextInt() as a For loop statement produces half the expected random value

Including nextInt() as a statement in a For loop produces different results than assigning a random value to a variable. Example:

Random randomWorker = new Random();
int temp = randomWorker.nextInt((120)+1);
for(int i=0; i<temp; i++){
... //I create a list in this loop
}
System.out.println(createdList.length());

This will work and produce a list of expected random length - from 1 to 120 values. However, the following code does not:

Random randomWorker = new Random();
for(int i=0; i<randomWorker.nextInt((120)+1); i++){
... //I create a list in this loop, identical code as in the example above
}
System.out.println(createdList.length());

Repeated a hundred million times, several times, the maximum number of values saved was 62.

What is the reason for this difference?




Aucun commentaire:

Enregistrer un commentaire