Tino APCS

Random

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.

  • The constructor is very basic and requires no arguments. The word “pseudorandom” just indicates that the number is not completely random.
  • Computers are not physically capable of creating true random numbers. Therefore, in Computer Science, we refer to computer generated random numbers as “pseudorandom.”

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.

Using Random

The Random class has many uses.

  • Most board games you have played probably use six sided dice to give the game an element of chance.
  • Video and computer games also use randomness to determine whether you hit your enemy or not, modified by the skill of the character you are using.
  • Think about the lottery as well. Without an element of chance, it would be pretty boring to buy lottery tickets and the game would cease to exist.

Last modified: December 12, 2022

Back to Point2d.double

Dark Mode

Outline