Random dice role program in Java
Welcome, in this tutorial we create a dice program in java that generates a random number between 1 to 6. we use a java.util.Random class to generate the numbers between the specific range.
Learn more about java.util.Random.
Code with explanation: Random dice role
import java.util.Random; import java.util.Scanner; public class DiceExample { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the dice roll count: "); int numberOfDice = input.nextInt(); if (numberOfDice == 0) { System.out.println("Input rollcount is 0" + "\n" + "Number of dice incremented to 1."); numberOfDice++; } diceRolled(numberOfDice); input.close(); } public static void diceRolled(int a) { int dice; int result = 0; int total = 0; Random randomObj = new Random(); System.out.print("Dice rolled : "); for (dice = 1; dice <= a; dice++) { result = randomObj.nextInt(6) + 1; total += result; System.out.print(result + " "); } System.out.println("\n" + "Total = " + total); } }
When the user enters 0, the output is.
Output Enter the dice roll count: 0 Input rollcount is 0 Number of dice incremented to 1. Dice rolled : 6 Total = 6
When the user enters a value greater than 0, the output is.
Output Enter the dice roll count: 2 Dice rolled : 2 3 Total = 5
Explanation
- In the main body, The code starts by creating a Scanner object called input.
- The code prints “Enter the dice roll count: “ and asks for an integer value from the user.
- If the number of dice is 0, then it increments to 1 and executes the following line of code.
- Line 14, code calls a function named diceRolled() that takes in an integer value as its argument.
- Line 18, The function calculates how many times each dice has been thrown and displays the result on the screen with the total value of the result.
That’s enough for a quick overview of the Random dice role program in Java.
Leave a Reply