-2

An assignment I'm working on right now needs to generate a random number from 1 to 4 using SecureRandom that will be used for a switch statement. Cases have to start from 1 so I can't just use

SecureRandom rand = new SecureRandom();
int a;
a = rand.nextInt(4);

right? I have to use SecureRandom to generate the integer as well.

Shanklen
  • 11
  • 4

1 Answers1

2

You're off by one (a very common source of errors). Of note is that rand.nextInt(n) will return a value from 0 to n - 1. You want

int a = 1 + rand.nextInt(4);

Also, make sure you reuse that SecureRandom instance (don't recreate it in a loop for example).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249