dimanche 3 octobre 2021

Best Way to get a random number

I need a number generator to return either a 0 or 1, which would then lead to different code to be executed depending on what number is generated.

Out of the below 2 options, is one method going to be better at randomising the chances of a 0 or 1, or would there be no difference?

Option 1

import java.util.Random;

private static final Random random = new Random();

int randInt = random.nextInt(2);

if (randInt == 0) {
   /* Code Here */
} else {
   /* Other Code Here */
}

Option 2

import java.util.Random;

private static final Random random = new Random();

int num = random.nextInt(1000);
int randInt = num % 2;

if (randInt == 0) {
   /* Code Here */
} else {
   /* Other Code Here */
}



Aucun commentaire:

Enregistrer un commentaire