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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.104.95