Read Also: Nim Game Source Code in Java
Here in this program, we are getting the number of dice to be rolled from the user input.
Dice Roll Program in Java
Let's understand the problem with some examples:Example 1
Enter the number of Dice to be rolled: 2
3 2
Example 2
Enter the number of Dice to be rolled: 7
3 6 2 4 2 6 1
Java Program
Below is the Java program for rolling Dice: import java.util.Scanner;
import java.util.Random;
public class DiceRoll
{
public static void main(String args[])
{
System.out.print("Enter the number of Dice to be rolled: ");
// Initializing Scanner object to read input from user
Scanner scan = new Scanner(System.in);
// Reading the number of Dices to be rolled
int numberOfDice = scan.nextInt();
/* Creating Random class object to generate
random numbers */
Random randomNumber = new Random();
for(int i=0;i < numberOfDice; i++)
{
System.out.print(randomNumber.nextInt(6)+1);
System.out.print(" ");
}
}
}
Output:
Enter the number of Dice to be rolled: 4
3 6 1 5
Explanation
According to Oracle docs, the Random class nextInt(int) method returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive).
randomNumber.nextInt(6)+1
In the above code, nextInt(6) will return a random integer number between 0 and 5, but we need it from 1 to 6. That's why we need to add 1 to the nextInt(6) statement.
That's all for today. Please mention in the comments if you have any questions related to the dice roll program in java with source code.