June 2001
Intermediate to advanced
888 pages
21h 1m
English
You need to generate random numbers in a hurry.
Use java.lang.Math.random( )
to generate random numbers. There is no
claim that the random values it returns are very
good random numbers, however. This code
exercises the random( ) method:
// Random1.java
// java.lang.Math.random( ) is static, don't need to construct Math
System.out.println("A random from java.lang.Math is " + Math.random( ));Note that this method only generates double values. If you need integers, you need to scale and round:
/** Generate random ints by scaling from Math.random( ).
* Prints a series of 100 random integers from 1 to 10, inclusive.
*/
public class RandomInt {
public static void main(String[] a) {
for (int i=0; i<100; i++)
System.out.println(1+(int)(Math.random( ) * 10));
}
}
Section 5.14 is an easier way to get random integers.
Also see the Javadoc documentation for
java.lang.Math, and the warning in this
chapter’s Introduction about pseudo-randomness versus real
randomness.