I'm trying to make a program that 'rolls two dice' and combines the number and needs to keep going until a specific number is reached 7 or 11 but every time I run it it keeps going forever.
double total = 0;
while (total != 7 || total != 11) {
DecimalFormat x = new DecimalFormat("#");
double dice1 = Math.random() * 6 + 1;
double dice2 = Math.random() * 6 + 1;
double total = (dice1 + dice2);
System.out.println("Dice 1: " + x.format(dice1) + " Dice 2: " + x.format(dice2) + " Total: " + x.format(total));
}
I think its because the int total is set to 0 and isn't getting the total from the loop but how can i fix this?
Your while loop logic is not correct. The total will always not be 7 or not be 11. You want "and" instead, using &&. Change
while (total != 7 || total != 11) {
to
while (total != 7 && total != 11) {
Also, I don't know of any dice that yield non-integers, so I would cast the results to int and declare dice1, dice2, and total as ints.
It's because you shadow total and you need to test logical and (not or). I would also prefer to use Random and nextInt(int) like
int total = 0; // <-- don't shadow me.
Random rand = new Random();
while (total != 7 && total != 11) {
int dice1 = rand.nextInt(6) + 1; // <-- using rand.
int dice2 = rand.nextInt(6) + 1;
total = (dice1 + dice2); // <-- no double.
System.out.printf("Dice 1: %d Dice 2: %d Total: %d%n", dice1, dice2, total);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With