简体   繁体   中英

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!

您应该将此行放在while循环的最后一行

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

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM