In this tutorial, we will combine the random dice roll example with the while loop to code a Java program that continues rolling dice until the dice result is 6.
Java Program That Repeatedly Throws a Dice Until it is Six
Before Read: How to Make a Dice Roll in Java?
As the while loop's condition statement is whether the dice is 6 or not, we can repeat the loop until the dice 6 arrives. We can also store the number of dice in a counter variable.
int counter = 0;
System.out.println(counter + " th try: " + dice);
while (dice < 6);
System.out.println("Congratulations, you won on " + counter + "th try");
1th try: 1
2th try: 1
3th try: 2
4th try: 2
5th try: 4
6th try: 1
7th try: 6
Congratulations, you won on 7th try
© Copyright Vitademy 2021. All rights reserved.