So lets say I want to randomly choose from the set of two numbers 1
and 3
.
How do I go about doing that? Do I just assign int a
to 1
, int b
to 3
, and then do randomly select from a
and b
?
So lets say I want to randomly choose from the set of two numbers 1
and 3
.
How do I go about doing that? Do I just assign int a
to 1
, int b
to 3
, and then do randomly select from a
and b
?
If there are only two numbers to choose from then you can use the value of a boolean
, because it returns either true
or false
.
One-liner solution assuming that int a = 1
and int b = 3
:
int randomOfTwoInts = new Random().nextBoolean() ? a : b;
If you have a specific list of numbers then put them in list structure (an array works well). Then you have the easier task of looking for a random index in the range from 0 to last array index. This post lists strategies for doing that:How do I generate random integers within a specific range in Java?