Reputation: 29
import java.util.*;
public class Exam2_2 {
public static void main(String[]args) {
Random rand = new Random();
int roll = 0;
int roll2 = 0;
int tries = 0;
while((roll % 2 == 0) && (roll2 % 2 == 0)) {
roll = rand.nextInt(8) + 1;
roll2 = rand.nextInt(8) + 1;
System.out.println("(" + roll + ", " + roll2 + ")");
tries++;
}
System.out.println("you won after " + tries + " tries");
}
}
My assignment is to simulate rolling two 8-sided dice and only stop once both numbers are even. I'm not sure what I'm doing wrong and have tried a bunch of different things to see if it would work the way I need it to work. Any advice would be much appreciated. Thanks.
Upvotes: 0
Views: 62
Reputation: 13483
The problem is in your while
condition:
while( (roll % 2 == 0) && (roll2 % 2 == 0) )
That means that while roll
is even and roll2
is also even, it'll do the stuff inside that block.
But, you want it to continue looping while their NOT both even, and stop when they are.
So you should change your condition to this:
while( !( (roll % 2 == 0) && (roll2 % 2 == 0) ) ) // they're NOT both even
or you could do this for better clarity:
while( (roll % 2 != 0) || (roll2 % 2 != 0) ) // at least one of them is odd
This way, the condition will be false
when they're both even, thus stopping the loop.
Upvotes: 0
Reputation: 201439
This seems like the perfect time to use a do {} while
to me, something like
Random rand = new Random();
int tries = 0;
int roll;
int roll2;
do {
roll = rand.nextInt(8) + 1;
roll2 = rand.nextInt(8) + 1;
System.out.printf("(%d, %d)%n", roll, roll2);
tries++;
} while ((roll % 2 != 0) || (roll2 % 2 != 0)); // <-- while roll or
// roll2 is odd.
System.out.println("you won after " + tries + " tries");
Or, You can use DeMorgan's Law and replace ((roll % 2 != 0) || (roll2 % 2 != 0))
with
while (!((roll % 2 == 0) && (roll2 % 2 == 0)));
that is, while NOT (roll
is even and roll2
is even).
Upvotes: 2