Supernaturalgirl 1967
Supernaturalgirl 1967

Reputation: 289

do while loop not working? Java

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?

Upvotes: 1

Views: 120

Answers (2)

Jonathan M
Jonathan M

Reputation: 17441

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 &&.

Upvotes: 3

Louis Wasserman
Louis Wasserman

Reputation: 198023

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.)

Upvotes: 0

Related Questions