Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String-Conditionals in a Java While Loop

Tags:

java

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;
    }
like image 665
Grant Park Avatar asked Dec 05 '25 13:12

Grant Park


2 Answers

Refer to De-Morgan's laws:

(NOT a) OR (NOT b)

is actually

NOT (a AND b)

You need to have && instead of ||.

like image 198
Maroun Avatar answered Dec 07 '25 03:12

Maroun


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();
}
like image 32
roeygol Avatar answered Dec 07 '25 05:12

roeygol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!