我的循环运行了一个额外的时间,我不明白为什么

时间:2016-05-18 16:26:25

标签: java

我有一个石头剪刀游戏,应该继续运行,直到一个玩家获得4连胜。一切似乎都能正常运作,但是当一个玩家获得连续4次胜利时,游戏会再运行一次,我不明白为什么。

//发表声明

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

//这个东西都在圈内,但我只会张贴一段。它是所有相同的

        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;
        }

//在循环结束时是这个

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

输出是这样的:

    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

如果有人能指出我正确的方向,那就太好了。 谢谢!

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您可以在循环开始时设置完成条件。这意味着即使player2连续4次获胜,在下一个循环开始之前,done也不会设置为true。将此行移至while循环的末尾:

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

答案 2 :(得分:0)

要在连续4次获胜后立即关闭循环,应在循环结束时检查退出条件,而不是在NEXT循环开始时。如果您在循环开始时检查退出条件,请将其作为重写的一部分 $retcode = shell_exec('which antiword'); if ($retcode) { $outtext = shell_exec('antiword -x db myfilename'); }

while (!done){...}