Often, you will need to generate and use random numbers in your applets. As it is with the rest of Java, there are several ways of generating random numbers (including writing your own code!). Again, for you the beginner, we will take the simplest approach. And, it is very easy!
To generate a random number, all you have to do is use the method Math.random(). For example, the statements below, illustrate this:
double x;
x = Math.random();
The Math.random() method comes from the java.lang.Math class, as indicated by the use of the prefix, Math, above (this is the conventional way of using the Math class as the presence of the class name, immediately implies its use).
Each call to the Math.random() method returns a value of type double that lies between 0.0 and 1.0 (not inclusive). Thus, the value of the variable, x above is set to some random value between 0.0 and 1.0. This method guarantees that the values are uniformly distributed and it always yields a different sequence of numbers each time a program using it is run.
Exercise: Write a short Java program that generates 10 random numbers as described above and prints them out to the Console Window. Run your program several times to confirm that it generates different values on each run.
Typically, your need for a random number will be very different from the kind supplied by Math.random(). For example, in order to simulate the tossing of a fair coin (i.e. generating a number 0 representing heads, or 1 representing tails), you will require two integer values. This is fairly easy to accomplish as you can see on the following page.
int outcome:
dice = (int) (Math.random() * 2); // generates either a 0 or 1
The expression above first generates a random number in the range [0.0 .. 1.0] and then multiplies it by 2, thereby giving a number in the range [0.0 .. 2.0], and then casting it as an integer, truncating it, giving either a 0 or a 1. Got it? Make sure you figure this out and understand it fully.
Exercise: Write an applet that generates several hundred random lines and draws them. What would you need to do to draw each line in a random color? Try drawing other random-colored objects like circles, rectangles, etc. of random sizes. Make sure that the coordinates generated always lie within the bounds of the applet.
Here are some other examples of generating random numbers:
-
Simulating a six-sided dice (i.e. outcome a is a number between 1 and 6):
int outcome = 1 + (int) (Math.random() * 6);
-
Generating a random number between 500 and 750:
int outcome = 500 + (int) (Math.random() * 250);
-
Generating a random number between 6.0 and 9.0:
double outcome = Math.random() * 3.0 + 6.0;
As mentioned above, there are several other ways of generating random numbers. There is even a separate class devoted to customizing the generation of random numbers (java.util.Random). However, unless your needs are very sophisticated, the simple Math.random() method discussed here will suffice.
