0

i am trying to make a big loop for console application in java, it works but after every step, for example after pressing "a" (code, corresponding to "a" letter) works , but every time it writes :"Your input is not correct, please try again", i don't understand why

boolean inputIsValid = false;
            while (!inputIsValid) {
                String input = reader.readLine();
                if (input.equals("a")) {
                    .....

                }
                if (input.equals("p")) {

                   .....

                }


                if (input.equals("q")) {
                    break;
                }
                else {
                    System.out.println("Your input is not correct, please try again");
                }
            }

1 Answer 1

2

Your final else block is only connected to the "q" condition, not to all the others. So it will execute every time that the input is not equal to "q".

You would see this happening if you stepped through the code (a hint for next time :).

You want a real if-else chain, like this:

if (input.equals("a")) {
    .....    
}
else if (input.equals("p")) {    
   .....    
}        
else if (input.equals("q")) {
    break;
}
else {
    System.out.println("Your input is not correct, please try again");
}
Sign up to request clarification or add additional context in comments.

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.