Monday, September 24, 2012

Generating a random number

also see Using the Random class to generate a random int

The Math class contains a static method for random number generation.

To generate a single random int between 0.0 and 1.0 you can use the following:

int number = (int)(Math.random() * 10);


This method returns a value from 0.0 to 0.9. A whole number, from 0 to 9, can be produced by multiplying the result by 10.

Note that casting has been used to convert the return value, which is a double, to int.

And remember, static class methods may be called without creating an instance of the class.

Where many random numbers with a larger range are required, see java.util.Random such as below:

In this example we are going to generate random numbers between 1 and 100:


The statement rand.nextInt(100) + 1 gets the next random number in the range of 1 - 100 inclusive. Need a large number? Adjust to suit.


No comments:

Post a Comment