O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generating Random Numbers

Problem

You need to generate random numbers in a hurry.

Solution

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));
    }
}

See Also

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required