简体   繁体   中英

How can I rerun a while loop after exiting?

I have the following code: How can I run the while loop again after exiting? The reason is, after a game of tictactoe has finished, I exit the while loop. This is when I ask the user if they want to play again. If the user types in "y", I would like to return to the beginning of the while loop. Thanks in advance.

        while(game.getGameState()!=GameState.XWIN &&
                game.getGameState()!=GameState.OWIN &&
                game.getGameState()!=GameState.DRAW ) {

            players[0].play(game);
            if(game.getGameState()!=GameState.XWIN) {
                players[1].play(game);
            }
        }

One way would be to nest your current while loop in an outer while loop, for example:

boolean quit = false;
while (!quit) {
    // Start Game....

    while(game.getGameState()!=GameState.XWIN &&
            game.getGameState()!=GameState.OWIN &&
            game.getGameState()!=GameState.DRAW ) {

        players[0].play(game);
        if(game.getGameState()!=GameState.XWIN) {
            players[1].play(game);
        }
    }

    // Game finished, ask to play again.
    int result = JOptionPane.showConfirmDialog(null, "Do you want to play again?", 
            "Play Again?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    if (result != JOptionPane.YES_OPTION) {
        quit = true; // if Yes is not selected then quit.
    }
}

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