String-Conditionals in a Java While Loop

后端 未结 3 1423
死守一世寂寞
死守一世寂寞 2021-01-21 18:25

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 re

相关标签:
3条回答
  • 2021-01-21 19:20

    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.");
             }
        }
    }
    
    0 讨论(0)
  • 2021-01-21 19:25

    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();
    }
    
    0 讨论(0)
  • 2021-01-21 19:30

    Refer to De-Morgan's laws:

    (NOT a) OR (NOT b)
    

    is actually

    NOT (a AND b)
    

    You need to have && instead of ||.

    0 讨论(0)
提交回复
热议问题