My question is how do I restrict user input to Y/N or y/n(in Java). Currently i'm using the equals() and plan to change them to equalsignorecase(), this should take care of the case part. However, this doesn't stop the user from entering other characters(ex: H or h). Currently when a character besides y or n is entered program proceeds straight to "thanks for playing message" and the end of the game.
I am relatively new to programming, so please provide examples with suggestion, preferably a complete example. It really goes a long way with me. Additional, if you feel this section of code could be written in a better way, I am open to rewrites, but once again please provide a full example.
I realize this question is a little broad for stackoverflow but I could really use the insight of more experienced programs. Thank you for your time.
// 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...");
}
}
}
}
}