xX_Dabman69_Xx xX_Dabman69_Xx - 12 days ago 4
Java Question

How to randomize between given number in Java?

I'd like to know how to randomize between already given values.

let's say I want a number that's either '20', '30', or '70'.
is there a way I can specify random values in

rnd.nextInt()
or do I have to use some workaround method?

tried to do it the following way,but it takes forever for the program to run (literally):

int specNum;
do {
specNum = rnd.nextInt(51)+20;
} while (specNum != 20 || specNum!= 30 || specNum != 70);

Answer

Create an array containing the values you want and generate a random index into the array:

int[] values = {20, 30, 70};
int specNum = values[rnd.nextInt(values.length)];
Comments