[an error occurred while processing this directive] CSE 142 Lab Resources: Random

University of Washington, CSE 142

Lab Resources: Random

Except where otherwise noted, the contents of this document are Copyright 2013 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges and Whitaker Brand

Basic lab instructions

Random

Randoms allow us to generate random* numbers. Just like with Graphics, where we made one pen that we used to draw on the DrawingPanel, we make one Random object and use that to generate Random values throughout our program.
import java.util.*;
     ...

Random randomName = new Random();

*Technically pseudorandom, because it's surprisingly hard to generate truly random values, but theyre random enough for this class!

Random syntax

Method name Description
nextInt() returns a random integer
nextDouble() returns a random real number in the range [0.0, 1.0).
nextInt(max) returns a random integer in the range [0, max). In other words, the number can be 0, (max - 1), or any integer between.
   int x = randomName.nextInt(5); // x is 0, 1, 2, 3, or 4
   double y = randomName.nextDouble();