java - 在 while 循环中要求用户再次玩的位置(猜谜游戏)

标签 java methods while-loop

这是一个生成 1-100 之间的随机数字并提示用户猜测数字的游戏。玩完一场游戏后(用户猜对了数字),游戏会建议您再玩一次。它应该在每次游戏后询问,直到用户拒绝为止。

在我的代码中,第一个完成的游戏将问题返回给用户,但之后的游戏不会询问,而是自动玩游戏。我在 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);

        }

最佳答案

您应该在每次迭代结束时阅读用户答案:

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
}

关于java - 在 while 循环中要求用户再次玩的位置(猜谜游戏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59081827/

相关文章:

java - 在离开字段时,而不是在 Vaadin 8 Binder 中输入用户类型时,更少地运行 validator

java - 两个构造函数和静态字符串变量

linux - 如何执行 while 循环并将字符串重定向到其中

java - 字符串索引越界? (Java,子串循环)

selenium - DesiredCapabilities 类型未定义方法 firefox()

c - C-使用fgets直到换行符/-1

java - AsyncTask 在后台运行时看不到 ProgressDialog

具有数据库支持最佳实践的 Java 枚举

java - 如何制作碰撞

c++ - 子类递归方法调用