Two-dice Gotcha!

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

No. You can use one random number generator to simulate both dice. Use it once for one die, then again for the other.

Two-dice Gotcha!

In fact, if you use two random number generators, you need to be careful. The following code:

Random rand1 = new Random();
Random rand2 = new Random();

will most likely produce two random number generators which are initialized to the same seed, and which will produce the same pseudorandom sequence. This is not what you want. The reason this happens is because Random() uses a seed based on the current time in milliseconds, but the current time changes little between the execution of the two statements. You could initialize the second random number generator using a random number from the first, but it is more convenient to use just one random number generator.

Throwing one die twice and adding up each outcome is equivalent to throwing two dice and adding up each die. However, throwing a 12-sided die once is not equivalent to throwing two 6-siced dice.

QUESTION 8:

Do you ever need more than one random number generator?