As the name suggests, the java.util package is full of utility classes that you will find very useful. Many of them are going to be far too advanced for what you need at this stage, but as you progress in skill, you should browse through the classes and see which ones you begin to understand. During this course, you will learn several of the util classes in detail, but for now we will just concentrate on this one: java.util.Random.
Random is probably the most fun of all the classes in the java.util package! Any sort of game or in depth simulation (such as inspecting a transportation system to see how efficient it is) will generally need some sort of randomness in order to work the way we want. That’s where the Random class comes in. Let’s take a look at it now.
| Constructor Summary |
|---|
**Random**() Creates a new random number generator. |
| Method Summary | |
|---|---|
double |
nextDouble() Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence. |
int |
nextInt(int n)| Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. |
These are the methods that you will be likely to find the most useful.
Let’s look at a situation where we might use this class. Consider an electronic raffle for a prize. There are 200 participants with one number each between 1 and 200. We can create an object of type Random to determine who the winner is.
Random chooser = new Random();
int winner = chooser.nextInt(200) + 1;
This code will give us a value between 1 and 200 in our winner variable.
RandomThe Random class has many uses.
Last modified: December 12, 2022
Back to Point2d.double