如果用户未选择是/否继续,则程序完成 - 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 :)");
}
}

尝试更改 else 条件块,如前所述。将weArePlaying1将导致它再次进入 while 循环。

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

最新更新