Written by Danielle Kain and Lisa Yan
RandomGenerator rgen = new RandomGenerator();
int randomInt = rgen.nextInt(); //Returns a random int
double randomDouble = rgen.nextDouble(); //Returns a random double
Color randomCol = rgen.nextColor(); //Returns a random color
boolean randomBoolean = rgen.nextBoolean(); //Returns a random boolean
The default method call (with no arguments) returns an unbounded integer, which could be very large or very small. To restrict the range of the integers you get, you can specify bounds. So to get an integer between 0 and 10, inclusive, you could do the following:
int lb = 0;
int ub = 10;
int x = rgen.nextInt(lb, ub); // integer in the range [0,10]
The default method call returns a double between 0.0 and 1.0. To increase the range of doubles, you can specify bounds:
double y = rgen.nextDouble(-3, 5.5); // note -3 is casted from integer to double -3.0
Unlike integers and doubles, there is a single argument p
that defines the behavior of rgen.nextBoolean(p)
:
true
with probability p
.false
with probability 1-p
.p
must be a double between 0 and 1.0.p
is 0.5.
bool equalProb = rgen.nextBoolean();
bool unequalProb = rgen.nextBoolean(0.75); // returns true 3/4ths of the time