我的问题是如何将用户输入限制为 Y/N 或 y/n(在 Java 中)。目前我正在使用equals()并计划将它们更改为equalsignorecase(),这应该处理案例部分。但是,这不会阻止用户输入其他字符(例如:H 或 h)。目前,当输入 y 或 n 以外的字符时,程序直接进入“感谢播放消息”并结束游戏。
我对编程比较陌生,所以请提供带有建议的示例,最好是完整的示例。这对我来说真的有很长的路要走。另外,如果您觉得这部分代码可以以更好的方式编写,我愿意重写,但请再次提供一个完整的示例。
我意识到这个问题对于stackoverflow来说有点宽泛,但我真的可以利用更有经验的程序的洞察力。感谢您的时间。
// creates instance of BufferedReader
// prompts user to play the game again
// places user input in a try
// if user wants to play again, call startGame()
// if user dosen't want to play again, keep asking anyways
private void showPlayAgainMessage()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("Do you want to play again? (y/n)");
try
{
String playAgain = br.readLine();
// Do you want to play again? Is y.
if(playAgain.equals("y"))
{
startGame();//else prompt another question with if else
}
// Do you want to play again? Is n.
else if(playAgain.equals("n"))
{
System.out.println();
System.out.println("Last chance. Play again? (y/n)");
playAgain = br.readLine();
// Last chance. Play again? Is y.
if(playAgain.equals("y"))
{
startGame();
}
// Last chance. Play again? Is n.
else if(playAgain.equals("n"))
{
System.out.println();
System.out.println("How about Minesweeper? (y/n)");
playAgain = br.readLine();
// How about Minesweeper? Is y.
if(playAgain.equals("y"))
{
System.out.println();
System.out.println("I really wish we had Minesweeper...");
System.out.println("Lots of Hangman though...Hangman? (y/n)");
playAgain = br.readLine();
// Lots of Hangman though...Hangman? Is y.
if(playAgain.equals("y"))
{
startGame();
}
// Lots of Hangman though...Hangman? Is n.
else if (playAgain.equals("n"))
{
System.out.println();
System.out.println("ok...");
}
}
}
}
}