我有一个程序正在询问用户一周中的一天。我正在尝试测试用户给出的答案,如果他们拼错一天或输入其他内容,则给他们另一个机会来回答。我等于等于不理会它的扫描仪,或者不管我输入哪一天都打印出while语句。

System.out.println("Great! Welcome back " + cust.getName() + ". What day of the week would you like "
            + "to book?(Sunday, November the 12th thru Saturday, November the 18th");

    String day = scan.nextLine();
    String dayLower = day.toLowerCase();
    scan.nextLine();


    while (!"monday".equals(dayLower) && !dayLower.equals("tuesday") && !dayLower.equals("wednesday")
            && !dayLower.equals("thursday") && !dayLower.equals("friday") && !dayLower.equals("saturday")
            && !dayLower.equals("sunday")) {
        System.out.println("Error in entry. Please enter a day of the week.");
        day = scan.nextLine();
    }

最佳答案

一种有效的方法是使用HashSet,这种检查是O(1)

static final Set<String> days = new HashSet<>(Arrays.asList(
       "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"));

public boolean isDay(String input) {
     return days.contains(input.toLowerCase());
}

10-08 17:03