Random Numbers
Home - About Us
 

Random Numbers

There are a couple of different ways to generate random numbers in Java.  One simple way is to the use Random class found in the java.util package. The Random class offers several methods for generating random values. Here we will just look at the nextInt(int) method -- the Java API for information on the other methods that are available.

First, you need to create a Random object:

	Random rand = new Random();

then call the nextInt method. Each call to the nextInt method will yield a randomly generated number from zero up to, but not including, the value passed to nextInt. For example, this call:

	int x = rand.nextInt(100);

will generate some number from zero to 99 (inclusive).

Math.random

Another way to generate random values is via a call to the random method in the Math class:  

    Math.random( )

The Math.random() method returns a double somewhere in the range of 0.0 up to, but not including, 1.0 (i.e., up to 0.9999999).  Although this range of random numbers can be useful, often a programmer wants other ranges of numbers, such as random integers in the range of 1 to 6 to simulate the roll of a die in a dice game.  The result of the Math.random method can be easily manipulated to various ranges of random integers.  For example, to generate random numbers from 1 to 100, use:

	int x = (int) (Math.random() * 100 + 1)

To generate random numbers in the range 405 to 409 (i.e., 405, 406, 407, 408 and 409):

	int num = (int) (Math.random() * 5 + 405)

Here is a discussion of the details of the random number formula (in this example I discuss the expression used to create random numbers in the range 1 to 4).

Home - About Us
Copyright © 2006 by Kiowok, Ann Arbor, Michigan, USA