user3516525
user3516525

Reputation: 43

My loop is running one extra time and I can't see why

I have a rock paper scissors game that is supposed to keep running until one player gets 4 consecutive wins. Everything seems to work correctly, but when one player gets the 4 consecutive wins, the game runs ONE extra time and I don't see why.

//THE WHILE STATEMENT

while(!done){       
    done=play1Win.consecutiveWins==4||play2Win.consecutiveWins==4;
    player1Roll=random();
    player2Roll=random();

//THIS STUFF IS ALL INSIDE THE WHILE LOOP BUT I WILL ONLY POST A SECTION OF IT. IT'S ALL THE SAME

        if(player1Roll==SCISSORS&&player2Roll==PAPER){
        System.out.println("Scissors beats Paper! Player 1 wins");      
        lastWinner=PLAYER1;

        if (lastWinner==PLAYER1){
        play1Win.consecutiveWins++;
        play2Win.consecutiveWins=0;
        }
    }
    if(player1Roll==PAPER&&player2Roll==ROCK){
        System.out.println("Paper beats Rock! Player 1 wins");      
        lastWinner=PLAYER1;

        if (lastWinner==PLAYER1){
        play1Win.consecutiveWins++;
        play2Win.consecutiveWins=0;
        }

//AT THE END OF THE LOOP IS THIS

      System.out.println("Player 1 wins- " +play1Win.consecutiveWins );  
      System.out.println("Player 2 wins- " +play2Win.consecutiveWins);

And the output is this:

    Paper beats Rock! Player 2 wins
    Player 1 wins- 0
    Player 2 wins- 1
    Paper beats Spock! Player 2 wins
    Player 1 wins- 0
    Player 2 wins- 2
    Rock beats Scissors! Player 2 wins
    Player 1 wins- 0
    Player 2 wins- 3
    Rock beats Scissors! Player 2 wins
    Player 1 wins- 0
    Player 2 wins- 4     // SHOULD STOP HERE
    Paper beats Rock! Player 1 wins    
    Player 1 wins- 1
    Player 2 wins- 0

If anyone can point me in the right direction, that would be great. Thanks!

Upvotes: 0

Views: 632

Answers (3)

Garun
Garun

Reputation: 22

To close the loop immediately after 4 consecutive wins, exit criteria should be checked at the end of the loop not at the beginning of the NEXT loop. If you check exit criteria at the beginning of the loop, make it part of your while like rewriting while (!done){...}

to

while(play1Win.consecutiveWins==4||play2Win.consecutiveWins==4){ ... }

Upvotes: 0

Olly Ludovino
Olly Ludovino

Reputation: 1

You set your done condition at the beginning of the loop. This means that even though player2 has 4 consecutive wins, done doesn't get set to true until the next loop has already started. move this line to the end of the while loop:

  done=play1Win.consecutiveWins==4||play2Win.consecutiveWins==4;

Upvotes: 0

inafalcao
inafalcao

Reputation: 1452

You should put this line at the last line inside the while loop

done=play1Win.consecutiveWins==4||play2Win.consecutiveWins==4;

Upvotes: 1

Related Questions