In order to understand classes and objects better and to get used to using them in programs, it is a good idea to practice with them. Soon we will build our own classes, but for now we will just work with some predefined classes in Java and write some static methods.
Java has many predefined classes that we can use in our programs in two ways:
The Random class in Java is a predefined class that enables the programmer to generate pseudo-random numbers. These are useful for simulations and scientific experiments. The methods in the Random Class are instance methods, not static methods. Thus, to use it we must first create a Random object, then use that object to generate our random numbers. Look up the Random class in the Java API and note that many of the methods have the same name as those we saw in the Scanner class. This is because in a way they are similar -- objects of both Scanner and Random produce sequences of values, but the Scanner class obtains them from the input stream while the Random class generates them using an algorithm.
Write a Java program that will simulate rolling 2 six-sided dice, and keep track of how many times each possible result (2, 3, ... 12) occurs.
First "roll" the dice 100 times and calculate the fraction of the "rolls" that resulted in each of the values (2, 3, ... 12). Compare these fractions with the probabilistic values for each number:
| Value | Fraction |
|---|---|
| 2 | 1/36 |
| 3 | 2/36 |
| 4 | 3/36 |
| 5 | 4/36 |
| 6 | 5/36 |
| 7 | 6/36 |
| 8 | 5/36 |
| 9 | 4/36 |
| 10 | 3/36 |
| 11 | 2/36 |
| 12 | 1/36 |
Next "roll" the dice 100000 times and calculate the fractions again. Again compare them to the probabilistic values. Do they match up better with the values this time? Make sure you understand why.
Complete your program in the following way:
Write a static void method called RollDice
that has two parameters: an int and a Random. The
int parameter determines how many times to
roll the dice and the Random is used to generate the actual values (note: we
could make the Random variable local to the method, but that would create a new
object with each call, which is not necessary). Think carefully about which
method in Random to call and how to appropriately generate the actual roll
values. In the method do the "rolls" and count how many times each number comes
up. Then print out the number of times each number comes up and its fraction
out of all of the rolls.
In the main program create the Random object, then enter a conditional loop. At each iteration of the loop ask the user to enter the number of rolls desired and call RollDice with the appropriate parameters. Then ask the user if he/she wants to continue. If so, repeat the process; if not terminate the program.