Simulating a dice roll in Java

posted Sep 12, 2020 1 min read

Random numbers play a major role in the programming field in terms of probability and equal distribution.

Imagine a cards game where 4 players are playing a game of hearts, but the cards are always dealt in the same way, and favoring a player over another. It will then slowly lose audience and/or get a bad feedback from the users.

Or a monopoly game where the dice gives the same number over and over. It will then become unplayable.

That’s where random numbers come in handy. A good and adequate understanding of this concept is crucial to develop a program that supports equality between several sides, or in basic debugging automation where multiple random cases should be tested, to make sure that the task is running as intended.

The random number generator works based on a parameter or a seed, and could generate a different sequence every time the parameter changes. However, if the same parameter is entered every time, it could generate the same sequence. And that’s why a specific approach to this concept got introduced, to ensure the total randomness of the created sequence.

This approach passes as a parameter to the number generator the current execution time of the program where it got implemented, which is totally different at every single moment.

In the following snippet, we’ll simulate 2 rolling dice, and we’ll keep rerolling until having the sum of the numbers on the 2 dice equal to a number entered by the user.

``````void rolling( int enteredNumber ) {
// The entered number should be between 2 and 12 or the loop will keep iterating infinitely

int die1, die2; // Numbers between 1 and 6 representing the dice.
int roll; // Total showing on dice
do {
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
roll = die1 + die2;
} while ( roll != enteredNumber );

}``````