Java Reference
In-Depth Information
Note that the value that we pass to the nextInt method is also the number of
possible values we can get in return. We can shift the range as needed by adding
or subtracting the proper amount. To get a random number in the range 1 to 6,
we can call nextInt(6) to get a value from 0 to 5, and then add 1.
The nextFloat method of the Random class returns a float value that is greater
than or equal to 0.0 and less than 1.0. If desired, we can use multiplication to
scale the result, cast it into an int value to truncate the fractional part, and then
shift the range as we do with integers.
The program shown in Listing 3.2 produces several random numbers in vari-
ous ranges.
LISTING 3.2
//********************************************************************
// RandomNumbers.java Author: Lewis/Loftus
//
// Demonstrates the creation of pseudo-random numbers using the
// Random class.
//********************************************************************
import java.util.Random;
public class RandomNumbers
{
//-----------------------------------------------------------------
// Generates random numbers in various ranges.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Random generator = new Random();
int num1;
float num2;
num1 = generator.nextInt();
System.out.println ("A random integer: " + num1);
num1 = generator.nextInt(10);
System.out.println ("From 0 to 9: " + num1);
num1 = generator.nextInt(10) + 1;
System.out.println ("From 1 to 10: " + num1);
 
Search WWH ::




Custom Search