简体   繁体   中英

Where to ask the user to play again within while loop (Guessing Game)

This is a game that generates a random number from 1-100 and prompts the user to guess the number. After playing one game (user guesses the number correct), the game offers you to play again. It should ask that after each game until the user declines.

In my code, the first completed game returns the question to the user but games after that do not ask and instead plays the game unprompted. Is my placement of the statement in the while loop incorrect?

public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        playGame(reader);
        System.out.println("Do you want to play again? ");


        String userInput = reader.next();
        int minGuess = 0;

        while(userInput.indexOf("y")!=-1 || userInput.indexOf("Y")!=-1) {
            guessCount = playGame(reader);
            game++;
            System.out.println("Do you want to play again?"); //not sure about this placement
        }

        overallStatistics(game, guessCount, minGuess);

        }

You should read the user answer in end of each iteration:

while(userInput.indexOf("y")!=-1 || userInput.indexOf("Y")!=-1) {
        guessCount = playGame(reader);
        game++;
        System.out.println("Do you want to play again?");
        userInput = reader.next(); // read user answer
}

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