Sometimes, it is useful to generate something randomly. Java has a tool specifically designed for the task, Random
.
Using Random
is very straightforward.
> import java.util.Random;
> Random myRandomGenerator = new Random();
> myRandomGenerator.nextInt();
java.lang.Integer res1 = -436551339
// Creates a random integer
> myRandomGenerator.nextInt(10);
java.lang.Integer res2 = 2
// Chooses a random number between 0 and 9 (1 less than 10).
> myRandomGenerator.nextInt(7);
java.lang.Integer res2 = 3
// Chooses a random number between 0 and 6 (1 less than 7).
> myRandomGenerator.nextBoolean();
java.lang.Boolean res3 = false
// Randomly chooses between true and false.
If you ever need to create another type of random information, check out the Random
documents to find the method you need.