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)