2

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;
    }
4
  • 2
    Use && not || as your conditional Commented Feb 3, 2015 at 20:47
  • You could also store the cities in an ArrayList and just do an if (!cityArray.contains(x)). This would also shorten your if-statement, especially if more cities are added later Commented Feb 3, 2015 at 20:53
  • your condition says that if userInput is not equal to A or B or C, please enter valid city. Problem is if you give valid input (eg. A), still it is not equal to B/C and hence still 'or' condition holds true. Change 'or' to 'and' Commented Feb 3, 2015 at 20:55
  • Think about it - if x contains "Amsterdam", then what does !x.equals("Amsterdam") return? What does !x.equals("Lexington") return? What does !x.equals("Madison") return? What happens when you || those things together? Commented Feb 3, 2015 at 21:05

3 Answers 3

9

Refer to De-Morgan's laws:

(NOT a) OR (NOT b)

is actually

NOT (a AND b)

You need to have && instead of ||.

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

1 Comment

It's actually NOT (a AND b)
1

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();
}

Comments

0

If you use Java 7 or above I would prefer the following code:

public String readCity() {
    while (true) {
        String x = keyboard.next();

        switch(x) {
            case "Amsterdam":
            case "Lexington":
            case "Madison":
                return x;
            default:
                System.out.println("Please enter a valid city.");
         }
    }
}

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.