简体   繁体   English

在哪里要求用户在 while 循环中再次玩(猜谜游戏)

[英]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.这是一款从 1 到 100 生成随机数并提示用户猜数字的游戏。 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?我在 while 循环中放置的语句是否不正确?

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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