Lesson 10Adding Randomness to Your Programs
We often want the ability to produce unpredictable behavior in our applications: to simulate rolling a die or flipping a coin in a game, for example. In this lesson, we will examine the use of the Random
class to do just that.
INITIALIZING THE RANDOM OBJECT
Doing things in the same way every time is important at times, but every now and again a bit of unpredictably is needed. In those situations, we use Random
, a class whose entire job is to mix things up.
We have to construct Random
before we can use it, but afterward, we've got a whole virtual box of crazy, random options. Let's look at a couple of the interesting things you can do with Random
.
Including the Random Class
By including an import of the Java Random
utility package, you can use a Random
class in your programs. This package is included by adding an import statement to the top of your listing with the name of the package. This is similar to what you did to include Scanner
in a previous lesson.
import java.util.Random;
The Random
class provides useful methods for automatically ...
Get Job Ready Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.