How to Generate Random Numbers

In the first article on generating random numbers, the focus was on generating whole numbers. Sometimes, however, it's useful to be able to generate random fractional numbers or even boolean values.

Generating a Random Number Between 0 and 1

There are two options to pick from when looking to generate a fractional number between 0 and 1. The first is to continue to use the Random object. The nextDouble() method will return a fractional number as a double data type:

`````` Random rand = new Random();
Double pickedNumber = rand.nextDouble(); ``````

which will produce a number like:

`` 0.823047216371369 ``

Note: there is a nextFloat() method which will also give you a random fractional number except that instead of returning a double data type it returns a float.

Alternatively, there is a simpler way that doesn't involve the need to explicitly create a random number generator object. Instead, the random static method from the Math class can be used:

`````` double pickedNumber = Math.random();
System.out.print(pickedNumber); ``````

Like the nextDouble() method the number produced is a double between 0 and 1:

`` 0.6563300920283471 ``

There is no real difference between the two options because the Math.random() method creates a random number generator of its own. It just saves you having to do so yourself.

Generally, I use Math.random() if I don't already have a random object created. For example, if I wanted to generate a random fractional number between 30.0 and 40.0 then I would create a Random object and use both the nextInt() and nextDouble() methods:

`````` Random rand = new Random();
int wholePart = rand.nextInt(10) + 30;
double decimalPart = rand.nextDouble();
double pickedNumber = wholePart + decimalPart;
System.out.print(pickedNumber); ``````

Which will produce a number like:

`` 34.831550232183766 ``

How to Generate Random Boolean Values

There is one more method of the Random class that is worth looking at.

It is the nextBoolean() method. It produces a true or false with almost equal probability. For example, if I wanted to write a program that simulated the tossing of a coin fifty times I could do this:

`````` boolean headsOrTails;
int tailsCount = 0;
Random rand = new Random();
for (int j=0;j < 50;j++)
{
`` The virtual coin landed on heads 27 times and on tails 23 times. ``