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.
Learn: Creating Objects and Calling Methods
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.
Your Turn
Let's try it in the Java Playground.
- Predict the range of values that can be generated.
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.
Your Turn
Let's try it in the Java Playground.
- Write a statement that will generate a random number between 1 and 6.
- Write a statement that will generate a random number between 10 and 50.
valueis assigned a randomintvalue between0and9.randomGradeis assigned a randomintvalue between1and100. The callintGenerator.nextInt(100)returns a random value between0and99, then we add1to the value making the range of possible values1to100.
int nextDouble()
This method returns a pseudorandom double value between 0.0 (inclusive) and 1.0 (exclusive).
Your Turn
Let's try it in the Java Playground.
- Predict the range of values that can be generated.
int nextBoolean()
This method returns a pseudorandom boolean value either true or false.
Your Turn
Let's try it in the Java Playground.
- Predict the range of values that can be generated.