1

I trying to make a do while loop that will keep looping till x either equals y or x equals 7 Here's the code:

else if(y == 4 || y == 5 || y == 6 || y == 8 || y == 9 || y == 10){
    System.out.println("Value point is: " + y);

    int x = rollDice();
    do{
        System.out.println("Roll again: " + rollDice());
        x = rollDice();
    }
    while(x != y || rollDice() != 7);

    if(x == y){
        System.out.println("You Win!");
    }
    if(x == 7){
        System.out.println("You Lose");
    }
    return;

}}

This is what an output looks like from it:

Dice roll is: 9
Value point is: 9
Roll again: 2
Roll again: 6
Roll again: 6
Roll again: 4
Roll again: 7
Roll again: 11
Roll again: 8
Roll again: 9
Roll again: 2
Roll again: 5
Roll again: 6
Roll again: 8
Roll again: 5
Roll again: 11
Roll again: 5
Roll again: 2
Roll again: 9
Roll again: 6
Roll again: 3
Roll again: 8
Roll again: 8
Roll again: 8
Roll again: 4
Roll again: 7
Roll again: 10
Roll again: 6
Roll again: 5
Roll again: 9
Roll again: 4
Roll again: 7
Roll again: 4
Roll again: 2
Roll again: 8
Roll again: 8
You Win!

Obviously 8 does not equal 9, and since there was a seven near the beginning it should have said "you lose" I just don't where I'm going wrong on this?

2
  • what's up with that part || rollDice() != 7);? you are throwing a bunch of rollDice(), but most of the time you don't affect it to x, making it effectively useless. Commented Oct 28, 2014 at 18:32
  • That was just a mistake I made, I fixed it once you guys pointed it out. Thanks for noticing it. Commented Oct 28, 2014 at 18:37

2 Answers 2

3

EDIT:

Please change the loop to this:

do{
    x = rollDice();
    System.out.println("Roll again: " + x);
}
while(x != y && x != 7);

You should only call rollDice() once per iteration. You were calling it 3 times each go-round. Also, the || needed to be changed to &&.

Sign up to request clarification or add additional context in comments.

3 Comments

I changed it, thanks for noticing that. But it still doesn't stop when x = y or x = 7.
It's a program to play craps so if the rollDice is 7 or 11 it prints win and if it is 3,2 or 12 it prints lose.
See the EDIT to my answer. You should only call rollDice() once per iteration. You were calling it 3 times each go-round.
0

It sounds like where you wrote

x != y || rollDice() != 7

you wanted

x != y && x != 7

(If you said you wanted to loop until "x either equals y or x equals 7", then you really want &&, not ||, in your condition.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.