I'm trying to prompt the user to give me one of three strings: "Amsterdam," "Lexington," and "Madison." If the user doesn't enter one of those strings, they should be repeatedly prompted until they do so.
When I type a string that's supposed to be acceptable, like "Lexington," I still receive "Please enter a valid city."
Can anyone tell me how the While loop is being run even when I'm negating the conditionals in it?
public String readCity() {
String x = keyboard.next();
while (!x.equals("Amsterdam") || !x.equals("Lexington") || !x.equals("Madison")) {
System.out.println("Please enter a valid city.");
x = keyboard.next();
}
return x;
}
Refer to De-Morgan's laws:
(NOT a) OR (NOT b)
is actually
NOT (a AND b)
You need to have && instead of ||.
You should use AND instead of OR like this:
String x = keyboard.next();
while (!x.equals("Amsterdam") && !x.equals("Lexington") && !x.equals("Madison")) {
System.out.println("Please enter a valid city.");
x = keyboard.next();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With