I created a dice simulator in Java that lets you choose how many dice you want to roll and then shows the result as ASCII art π¨.
π Full project on GitHub:
Dice Simulator β Source Code
In this post, Iβll break down the core ideas of the project step by step so even beginners can follow along.
π 1. The Goal
The simulator should:
Ask the user how many dice they want to roll.
Generate a random number (1β6) for each die.
Show the result using ASCII art (like β, β, β).
Handle mistakes (like typing letters instead of numbers).
This small project helps you practice:
Input handling
Random numbers
Loops
Clean method design
π» 2. Handling User Input
We use Scanner to read the userβs choice and a loop to make sure the input is valid:
Scanner input = new Scanner(System.in);
boolean appCompleted = false;
do {
try {
System.out.println("How many dice would you like to roll?");
int numberOfDice = input.nextInt();
if (numberOfDice <= 0) {
System.out.println("Please enter a positive number.");
continue;
}
appCompleted = true;
// Roll dice here...
} catch (InputMismatchException e) {
System.out.println("This is not a valid number.");
input.next(); // clear invalid input
}
} while (!appCompleted)
π Takeaway: Input must be checked! Without this, the program could crash if the user types something unexpected.
π² 3. Rolling the Dice
We use Random to simulate the dice roll:
Random random = new Random();
int rolledNumber = random.nextInt(6) + 1;
Why +1? Because nextInt(6) gives numbers from 0β5, but dice go from 1β6.
π Takeaway: This is how Java simulates randomness.
π¨ 4. Displaying Dice Faces
The coolest part: ASCII art!
static String display(int value) {
return switch (value) {
case 1 -> "---------\n| |\n| o |\n| |\n---------";
case 2 -> "---------\n| o |\n| |\n| o |\n---------";
// ... and so on for 3, 4, 5, 6
default -> "Not a valid die face";
};
}
This method maps numbers to pictures of dice. It uses a modern switch expression for clarity.
π Takeaway: Always separate βlogicβ (rolling) from βpresentationβ (printing). Makes your code much cleaner.
π‘οΈ 5. Putting It Together
When you run it:
Youβre asked how many dice to roll.
Each roll is random.
ASCII dice are displayed.
Invalid inputs donβt crash the program.
This shows defensive programming in action.
π 6. Possible Enhancements
Want to take this further? Try adding:
A roll until doubles feature.
A statistics counter (how often each face shows up).
A GUI version using JavaFX for real dice images.
π Full Code
π Dice Simulator in Java (GitHub Repo)
π― Final Thoughts
This project may be small, but it demonstrates important concepts in Java:
Input validation
Random number generation
Clean method separation
Defensive coding
π¬ Question for you:
If you were to improve this dice simulator, what would you add first β statistics, a GUI, or multiplayer mode?
Top comments (0)