Skip to main content
Lesson 18 - Boolean Algebra - Loop Boundaries
ZIPPDF (letter)
Lesson MenuPreviousNext
  
Generating Random Values page 6 of 8

  1. The casino game of craps involves rolling a pair of dice to generate random values within a specified range. Java has a class named Random that makes it easy to get seemingly random numbers into your program.

  2. To use the capabilities of the Random class, you must first import the class as follows:

    import java.util.Random;
  3. A Random object can then be constructed with a statement like

    Random die = new Random();

    and then use the nextInt method.

    /** From the Random class
     *
     * Returns a pseudorandom, uniformly distributed int
     * value between 0 (inclusive) and the specified value
     * n (exclusive), drawn from this random number 
     * generator's sequence.
     */
    public int nextInt(int n);

    (Note that because of the exclusion on the upper boundary mentioned in the above comment, nextInt(n) returns a random integer in the range, 0,1,...n-1.)

  4. For example, you can get a number from 1 to 6 with an expression like:

    // The message randomly returns 0, 1, 2, 3, 4, or 5.
    // A die is simulated by adding 1 to give a value
    //   in the range 1 - 6.
    int dieRoll = die.nextInt(6) + 1;
    
  5. The Random class contains additional methods for generating random longs, doubles, booleans, etc. Please consult the Java documentation for a complete explanation of its capabilities.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.