There is Random().nextInt()
method which generates a random integer from 0 (inclusive) to bound (exclusive).
Following is snippet for randomInteger(2, 5)
, this will generates a random integer between 2 (inclusive) and 5 (inclusive).
// import java.util.Random; static int randomInteger(int min, int max) { if (min >= max) { throw new IllegalArgumentException("max must be greater than min"); } Random r = new Random(); return r.nextInt((max - min) + 1) + min; }
Similar to random integers in Java, java.util.Random
class provides method nextDouble()
which can return uniformly distributed pseudo random double values between 0.0 and 1.0.
static double randomDouble(double min, double max) { if (min >= max) { throw new IllegalArgumentException("max must be greater than min"); } Random r = new Random(); return min + (max - min) * r.nextDouble(); }
Read about Decimal precision in Java .
Use java.util.Random
method nextBoolean()
to generate random boolean values in Java.
The following code snippet will show you how to pick a random value from an enum. I will use an enum
called Season
which will have four valid value. These values are WINTER, SPRING, SUMMER and FALL.
To allow us to get random value of this Season
enum we define a getRandom()
method in the enum
. This method use the java.util.Random
to create a random value. This random value then will be used to pick a random value from the enum
.
import java.util.Random; public class Example1 { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.printf("Season %d is %s%n", i, Season.getRandom()); } } private enum Season { WINTER, SPRING, SUMMER, FALL; public static Season getRandom() { Random random = new Random(); return values()[random.nextInt(values().length)]; } } }