Reputation: 97
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");
}
}
Upvotes: 0
Views: 521
Reputation: 103555
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");
}
Upvotes: 2