Using the Random Class
When we play games or run simulations, there is often an element of randomness involved. This makes each play through the game unique and more interesting. The Random
class is one way that we can generate random values.
Random Constructor
In order to use the Random
class, an object needs to be created.
Random randomGenerator = new Random();
Random Methods
We've compiled some helpful Random
methods below.
A complete list of Random
methods can be found in the Random API.
int nextInt()
This method returns a pseudorandom int
value. All int values are possible with approximately equal probability.
int nextInt(int bound)
This method returns a pseudorandom int
value between 0
(inclusive) and bound
(exclusive). All values in this range have approximately equal probability.
value
is assigned a random int
value between 0
and 9
.
randomGrade
is assigned a random int
value between 1
and 100
. The call intGenerator.nextInt(100)
returns a random value between 0
and 99
, then we add 1
to the value making the range of possible values 1
to 100
.
int nextDouble()
This method returns a pseudorandom double
value between 0.0
(inclusive) and 1.0
(exclusive).
int nextBoolean()
This method returns a pseudorandom boolean
value either true
or false
.
Resources