I'm wondering how I could get my dice rolling simulator to stop when it your total roll is one of 2 certain numbers, (example: rolling will stop when you reach a total roll of 7 or 12). Here is my code so far:
public class RollDice {
public static void main(String[] args) {
// TODO Auto-generated method stub
int dice1; // First Dice.
int dice2; // Second Dice.
int total; // Sum of the two rolls.
dice1 = (int)(Math.random()*6) + 1;
dice2 = (int)(Math.random()*6) + 1;
total = dice1 + dice2;
System.out.println("Your first roll is " + dice1);
System.out.println("Your second roll is " + dice2);
System.out.println("Your complete roll is " + total);
}
}
Ryan
2,0942 gold badges17 silver badges33 bronze badges
1 Answer 1
Just wrap everything with a do-while loop:
int total; // Sum of the two rolls.
do {
int dice1; // First Dice.
int dice2; // Second Dice.
dice1 = (int)(Math.random()*6) + 1;
dice2 = (int)(Math.random()*6) + 1;
total = dice1 + dice2;
System.out.println("Your first roll is " + dice1);
System.out.println("Your second roll is " + dice2);
System.out.println("Your complete roll is " + total);
} while (total != 7 && total != 12);
Or something to that extent. :)
See https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
answered May 12, 2015 at 22:34
Brian Topping
3,31532 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
hallibtch
For some reason it won't let me resolve total as a variable in the last line, why is this?
Brian Topping
Ah right, sorry about that, typing too fast. Answer edited.. :)
lang-java