Skip to content
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions
  • Author Profile: Govind

Simplified Learning Blog

Learning made easy

  • Java
    • Core Java Tutorial
    • Java 8
    • What is Rest API in java
    • Spring Framework
    • Type Casting in Java | 2 types Implicit and explicit casting
    • Spring Boot Tutorial
      • Spring Boot Rest API Example complete guide
    • Top 50 Java Interview Questions
    • JUnit 5 Tutorial
      • Assertall in JUnit 5
      • Assertions in JUnit 5
    • Java Thread Tutorials
      • How to create thread in Java
      • Multithreading in java
      • Daemon Thread in Java | How to create daemon thread in java
      • Top 40+ Multithreading interview questions
  • AWS
    • What is AWS (Amazon Web Services)
    • AWS IAM (Identity and Access Management)
    • AWS SNS | What is SNS
    • What is SQS | AWS SQS (Simple Queue Service)
    • What is AWS Lambda
    • Top 10 AWS Lambda interview questions
  • Java Codes
  • Software Architecture
    • Software Architecture Performance
    • Performance Principles of Software Architecture
    • System Performance Objective
  • Spring Boot Tutorial
  • Tools
    • JSON Formatter & Debugging Guide for Spring Boot Developers
    • Free Character Counter Tool: The Ultimate Guide to Counting Characters, Words, and Text Statistics
  • Tech Blogs
    • Java 21 New Features
    • Is Java Dead? Is java dead, 2023 ?
    • New Features in Java 17
  • Toggle search form

Java dice roll program

Posted on April 4, 2023November 22, 2025 By Govind No Comments on Java dice roll program

In this blog tutorials, we will see how to implement using java dice roll program.

Table of Contents

Toggle
  • Code Java Dice Roll Program
    • Code Explanation
  • What is dice roll ?
  • Advanced Java Dice Roll Program
    • Code advance dice roll program
    • Code Explanation
  • More Tech Details:
  • The Core Concept: Random Number Generation
    • 1. The Math.random() Method
    • 2. The java.util.Random Class (Recommended)
  • 💻 Java Implementation: Rolling a Single Die
  • 📈 Advanced Program: Rolling Multiple Dice
  • Java Dice Roll Program FAQs
    • 1. What is the difference between Random and Math.random()?
    • 2. Why do we always add + 1 to the result of random.nextInt(N)?
    • 3. What is “seeding” a random number generator and why would I use it?
    • 4. How can I ensure the random numbers are thread-safe in a multi-threaded application?
    • 5. How would I simulate weighted dice (i.e., making 6 more likely to appear)?
  • Conclusion

Code Java Dice Roll Program

package com.slb.java;
import java.util.Random;

public class DiceRollSLB {
    public static void main(String[] args) {
        Random random = new Random();
        int dice1 = random.nextInt(6) + 1;
        int dice2 = random.nextInt(6) + 1;
        System.out.println("Dice 1: " + dice1);
        System.out.println("Dice 2: " + dice2);
    }
}

OP: 1
Dice 1: 3
Dice 2: 5
OP: 2
Dice 1: 3
Dice 2: 6
OP: 3
Dice 1: 1
Dice 2: 

Code Explanation

The above program calculates rolling of a specified number of dice with a specified number of sides on each die, and prints out the results of each roll. In above example we have rolled it 3 times that means we ran this above program 3 times.

What is dice roll ?

Java dice roll program
Dice Roll

Rolling dices is a form of chance that involves rolling at least one die. Once rolled, the face value of the die will determine its outcome; and depending on how many sides there are on it, values ranging from 1 to 6 inclusive can be produced from that roll. Dice rolls are board games or gambling games in order to add an element of chance and uncertainty into gameplays.

Advanced Java Dice Roll Program

Code advance dice roll program

package com.slb.java;

import java.util.Random;
import java.util.Scanner;

public class AdvancedDiceRollSLB {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random random = new Random();
        int numDice, numSides;
        boolean isValid = false;

        // get number of dice and sides and then operate on the inputs
        while (!isValid) {
            System.out.print("Enter number of dice: ");
            numDice = input.nextInt();
            System.out.print("Enter number of sides on each die: ");
            numSides = input.nextInt();

            // check if inputs are proper valid ones
            if (numDice > 0 && numSides > 0) {
                isValid = true;
                int sum = 0;

                // roll each die and print the result on console
                for (int i = 1; i <= numDice; i++) {
                    int roll = random.nextInt(numSides) + 1;
                    System.out.println("Die " + i + ": " + roll);
                    sum += roll;
                }

                // print the sum of dice
                System.out.println("Total: " + sum);
            } else {
                System.out.println("Invalid input. Please enter positive integers.");
            }
        }
    }
}

Output:

Enter number of dice: 6
Enter number of sides on each die: 2
Die 1: 2
Die 2: 1
Die 3: 1
Die 4: 2
Die 5: 1
Die 6: 1
Total: 8

Process finished with exit code 0

Run #2

Enter number of dice: 2
Enter number of sides on each die: 2
Die 1: 1
Die 2: 1
Total: 2

Process finished with exit code 0

Code Explanation

This program called AdvancedDiceRoll AdvancedDiceRoll is an upgraded code version of a DiceRoll application which is there above at the start. This program lets you roll a certain number of dice, with an exact amount of faces on every die and then prints the outcomes from each roll, as well as the total of the rolls.

The program makes use of its random class to create random numbers for each die roll, and also the scanner class (used to scan data from the user) is used to obtain feedback from the person who is using it. Then, it asks the user to input numbers for the dice they want to roll as well as how many sides for the die. It it checks whether the input is valid (both inputs have to be integers that are positive).

When the inputs are valid, The program rolls the dies and outputs the result along with the total sum of all dies. In the event that inputs are incorrect, the program displays an error warning and asks the user to input valid data.

The program makes use of an endless loop to prompt the user to input data until input that is valid and ensures that this program can provide a an output that is valid.

Overall, Advanced Dice Roll program, a good program. AdvancedDiceRoll program is an sophisticated and flexible variation of DiceRoll code which allows users to choose the number of sides and dice of each die, and providing more detailed output.

More Tech Details:

Creating a simple dice roll program is a classic introductory exercise in Java. It demonstrates fundamental concepts like generating random numbers, user input, and basic control flow.

The Core Concept: Random Number Generation

The central component of any dice roll program in Java is the ability to generate a pseudo-random integer within a specified range (typically 1 to 6). Java offers two primary classes for this:

1. The Math.random() Method

This static method is part of the java.lang.Math class. It returns a double value between $0.0$ (inclusive) and $1.0$ (exclusive). To convert this into an integer roll for an N-sided die, you use a simple formula:

$$\text{Roll} = (\text{int})(\text{Math.random}() \times \text{Number of Sides}) + 1$$

2. The java.util.Random Class (Recommended)

This class offers more flexibility and better control over the random number generation process, including the ability to provide a specific seed. The nextInt(n) method returns a pseudo-random integer between $0$ (inclusive) and $n$ (exclusive).

To roll a standard 6-sided die, you call nextInt(6) (which gives 0 to 5) and add 1.

$$\text{Roll} = \text{random.nextInt}(\text{Number of Sides}) + 1$$

💻 Java Implementation: Rolling a Single Die

This example uses the preferred Random class to simulate a single roll of a standard 6-sided die.

Java

import java.util.Random;
import java.util.Scanner;

public class SingleDiceRoller {

    public static void main(String[] args) {
        // 1. Initialize the Random object once
        Random random = new Random();
        Scanner scanner = new Scanner(System.in);
        final int SIDES = 6;
        
        System.out.println("Welcome to the 6-Sided Dice Roller!");
        System.out.println("Press Enter to roll the die...");
        
        // Wait for user input (Enter key)
        scanner.nextLine(); 
        
        // 2. Generate the random number (0 to 5) and add 1 (1 to 6)
        int rollResult = random.nextInt(SIDES) + 1; 
        
        System.out.println("--------------------------------");
        System.out.println("|    Your roll is: " + rollResult + "    |");
        System.out.println("--------------------------------");
        
        scanner.close();
    }
}

📈 Advanced Program: Rolling Multiple Dice

A more robust program allows the user to specify the number of dice and the number of sides, demonstrating better parameter handling and looping.

Java

import java.util.Random;
import java.util.Scanner;

public class MultiDiceRoller {

    // Global Random instance for efficiency
    private static final Random RANDOM = new Random();

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("--- Advanced Dice Roller ---");
            
            // Get user input for number of dice
            System.out.print("Enter number of dice to roll (e.g., 2): ");
            int numDice = scanner.nextInt();
            
            // Get user input for number of sides
            System.out.print("Enter number of sides per die (e.g., 6 or 20): ");
            int numSides = scanner.nextInt();
            
            int totalSum = 0;
            System.out.println("\nRolling " + numDice + " D" + numSides + " dice...");

            // Loop to roll each die individually
            for (int i = 1; i <= numDice; i++) {
                // Generate roll: nextInt(N) returns 0 to N-1, so we add 1
                int roll = RANDOM.nextInt(numSides) + 1; 
                totalSum += roll;
                System.out.println("Die " + i + ": " + roll);
            }

            System.out.println("\n==================================");
            System.out.println("Total Sum of " + numDice + " dice: " + totalSum);
            System.out.println("==================================");
        } catch (java.util.InputMismatchException e) {
            System.err.println("Invalid input. Please enter only whole numbers.");
        }
    }
}

Java Dice Roll Program FAQs

1. What is the difference between Random and Math.random()?

Featurejava.util.RandomMath.random()
TypeClass (requires object instantiation)Static method
Return TypenextInt(n) returns intReturns double (0.0 to 1.0)
ControlAllows seeding (e.g., for reproducible results)Always uses a fixed, system-dependent seed
RecommendationPreferred for production code and multi-threaded environments.Suitable for quick, single-use random numbers.

2. Why do we always add + 1 to the result of random.nextInt(N)?

The method random.nextInt(N) returns a pseudo-random integer in the range $0$ (inclusive) up to $N$ (exclusive).

For a standard die with $N=6$ sides, the results are $0, 1, 2, 3, 4, 5$. Since a die roll must start at 1, adding 1 to the result shifts the range to $1, 2, 3, 4, 5, 6$.

3. What is “seeding” a random number generator and why would I use it?

Seeding is the process of setting the initial value used by the random number algorithm. If you initialize the Random object with the same seed value every time, the sequence of generated “random” numbers will be exactly the same.

  • Syntax: Random random = new Random(seedValue);
  • Use Case: Seeding is essential for testing (to reproduce bugs) and in simulations or competitive programming where the randomness must be predictable and verifiable.

4. How can I ensure the random numbers are thread-safe in a multi-threaded application?

While a single java.util.Random instance is generally safe for concurrent use, its performance can degrade under heavy contention. For high-performance multi-threaded applications, use java.util.concurrent.ThreadLocalRandom.current() instead.

ThreadLocalRandom provides a separate, optimized Random instance for each thread, avoiding resource contention and offering superior performance compared to a globally shared or synchronized Random object.

5. How would I simulate weighted dice (i.e., making 6 more likely to appear)?

You cannot simulate weighted probability directly using nextInt(). You must modify the range and mapping:

  1. Create a weighted range: Generate a random number across a larger range (e.g., 1 to 100).
  2. Map the results: Define segments of that range to correspond to the die faces. Give larger segments to the faces you want to be more probable.
Range (1-100)Die FaceProbability
1 – 10110%
11 – 20210%
21 – 35315%
36 – 60425%
61 – 80520%
81 – 100620%

Conclusion

In this blog, we have seen that we can use this Dice Roll program to calculate the dice roll chances that can be used as base logic in creating java based board games.

Checkout Java Tutorials here

Govind

For over 15 years, I have worked as a hands-on Java Architect and Senior Engineer, specializing in building and scaling high-performance, enterprise-level applications. My career has been focused primarily within the FinTech, Telecommunications, or E-commerce sector, where I’ve led teams in designing systems that handle millions of transactions per day.

Checkout my profile here : AUTHOR https://simplifiedlearningblog.com/author/

Related

Java Codes Tags:Java dice roll program, java program, java program for rolling dice

Post navigation

Previous Post: How to read Excel File using jxl
Next Post: Series program in java

More Related Articles

How to read Excel File using jxl Java Codes
Series program in java Java Codes
Calculate date of birth from age in jquery Java Codes
jcalendar in java swing example Java Codes
How to convert excel to PDF using java Java Codes
Java util date to String Java Codes

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Java Virtual Threads (Project Loom) in Real Enterprise Applications
  • Free Character Counter Tool: The Ultimate Guide to Counting Characters, Words, and Text Statistics
  • Understanding Java Sealed Classes
  • Top 50 Java Coding Interview Questions and Answers (2025 Updated)
  • Java Record Class Explained: Simple, Immutable Data Carriers

Recent Comments

  1. Gajanan Pise on Performance Principles of Software Architecture

Copyright © 2025 Simplified Learning Blog.

Powered by PressBook Green WordPress theme