Question

How can I generate random numbers?

Answer

Generating random numbers is simple. Provided as part of the java.util package, the Random class makes it easy to generate numbers. Start by creating an instance of the Random class

// Create an instance of the random class
Random r = new Random();

Now, you must request a number from the generator. Supposing we wanted an integer number, we'd call the nextInt() method.

// Get an integer
int number = r.nextInt();

Often you'll want numbers to fall in a specific range (for example, from one to ten). We can use the modulus operator to limit the range of the numbers. This will give us the remainder of the number when divided by ten (giving us a range -9 to +9). To eliminate negative numbers, if the number is less than one we'll add ten to it. This gives us random numbers between one and ten!

// Accept only up to ten
int random_number = number % 10;
if (random_number < 1) random_number = random_number + 10;

Creating random numbers in an application or applet really isn't that difficult. Just remember to limit the range of your numbers, and to import the java.util.Random class.


Back