# Simulating a dice roll in Java

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 );

}`````` How to print an array in java. Hasnain_khan - Oct 9, 2020 Creating Random alphanumeric String in java yoniortho - May 5 How to generate random numbers in java within range Hasnain_khan - Oct 13, 2020 Java random number between 1 and 11 amna - Oct 18, 2020 How do we use for-each loop in arrays muliemes - May 18 Find heighest and lowest of five integer using java loops Tania - Jul 18 How to loop through characters in a string java amna - Jul 2 How to generate a random string in Python mhfaisal - Jul 10 How to make a random number generator in c++ Sanjana Sagar - May 20 how to generate random numbers with a range in C++? Lalit Kumar - Apr 17, 2020