如果用户没有选择是/否继续,则程序结束 - java

时间:2018-05-09 16:42:15

标签: java

我有一点逻辑问题,我需要一些指导。基本上我问用户是否想再玩一次。如果他们选择是,那么他们再次播放,这很好。如果他们选择否则会给出一条感谢信息并且游戏结束(控制台停止)。这也很好。

我的问题是当用户没有输入是或否时。如果他们输入其他内容,则显示正确的消息,如果他们想要播放或不播放是或否,再次询问用户,然后游戏结束。

我可以看到问题是while循环仅在weArePlaying为1时有效。但是当它等于2时,它将退出循环,因此游戏结束。

所以我的问题是如何克服这个问题?

以下是我的代码的基本结构,您可以看到we are playing equals 1, 2 or 0

会发生什么
public static void main(String[] args) throws FileNotFoundException
{

    File file = new File("C:\\Users\\mmkp1\\Documents\\listofmovies.txt");
    int attempts = 10;
    Scanner scanner = new Scanner(System.in);

    int weArePlaying = 1;

    while (weArePlaying == 1)
    {

         ...

        // This is in the while loop and I think this is why it end abruptly
        // as the value for areWePlaying does not equal 1 if we don't select
        // 1 or 2

        if (weArePlaying == 2)
        {
            System.out.println("Do you want to play again? (yes/no)");
            String anotherGame = scanner.nextLine();
            if (anotherGame.equals("no"))
            {
                weArePlaying = 0;
            } else if (anotherGame.equals("yes"))
            {
                weArePlaying = 1;
                attempts = 10;
                guessedLetters.clear();
            } else
            {
                weArePlaying = 2;
                System.out.println("Do you want to play again? (yes/no)");
            }
        }
    }

    if (weArePlaying == 0)
    {
        System.out.println("Thank you for playing :)");
    }

}

1 个答案:

答案 0 :(得分:0)

尝试更改上面提到的else condtion块。将weArePlaying设为1会导致它再次进入while循环。

if (anotherGame.equals("no")) {
    weArePlaying = 0;
} else if (anotherGame.equals("yes")) {
    weArePlaying = 1;
    attempts = 10;
    guessedLetters.clear();
}
else {
    weArePlaying = 1;
}