1

am having trouble trying to validate a user response to exit my app or try again(its a simple game)? when the game finishes I ask the user if they want to continue type "y" for yes or "n" for no to exit. How can I validate their response so if its neither y or n I show an error message and ask them to type it again???

This doesn't seem to worK for me???

if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))

           System.out.println("Error enter y for yes and n for no");
            System.out.println("Would you like to play again (y/n):");
           choice = sc.next();
5
  • You need to post your full code, so we can help you. This snippet doesn't explains what or where is the error. Commented Feb 24, 2013 at 3:21
  • its the logic i need help with not really the code Commented Feb 24, 2013 at 3:26
  • The problem is not on the logic, but on the code. Commented Feb 24, 2013 at 3:30
  • no it was the logic, using an "if" statement doesn't end the program regardless of the code within, it needs to be in a "while" loop context for the code to work. Commented Feb 24, 2013 at 3:45
  • it was mearly a logic issues not a code issue that way i posted a snippet instead of my whole code. Commented Feb 24, 2013 at 3:48

2 Answers 2

2

Just change the

if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))

to

while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))

This will continue to ask them for another letter each time they don't choose the letter 'n' or 'y'.

EDIT: Also, you might want brackets around the code within the if (soon to be while) statement.

Sign up to request clarification or add additional context in comments.

Comments

0

Without any full context, difficult to give a relevant answer.

But you can already test your code with curly braces around the if statement:

if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
  System.out.println("Error enter y for yes and n for no");
  System.out.println("Would you like to play again (y/n):");
  choice = sc.next();
}

Indeed, with your current code, only the first line:

System.out.println("Error enter y for yes and n for no");

is taken in account by your condition.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.