Home > Mobile >  Best Way to get a random number
Best Way to get a random number

Time:10-04

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 */
}

CodePudding user response:

A simple way to generate a 1 or 0 is:

private static final int random = (int)(Math.random()*2);

This will generate a random number between 0 and 2 (not including 2), then round down to an int (only 0 and 1 are possible).

CodePudding user response:

In your comments you mentioned you wanted to extend it, using a switch would probably be best for that.

import java.util.Random;

private static final Random random = new Random();

const int NUM_OPTIONS = 2;

switch (random.nextInt(NUM_OPTIONS)) {
   case 0:
      functionOne();
      break;
   case 1:
      functionTwo();
      break;
   default:
      throw new Error("Unsupported value")
}
  • Related