You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中验证用户输入字符串是否匹配指定字符串数组,不合法则重新提示?

Hey there! Let's get this input validation working properly. First, quick heads-up: you've got a typo in your array—"Thusday" should be "Thursday" (you have it twice!). Fixing that first will avoid confusion later.

Here's the step-by-step logic you need to add:

  1. Use a loop to repeat input until valid: A do-while loop is perfect here because we want to prompt the user at least once, then keep asking until they enter a valid day.
  2. Check if the input exists in your valid day list: You can either loop through the array to compare each element, or convert the array to a Set for faster, cleaner lookups.
  3. Handle invalid inputs: If the user's input isn't in the list, print an error message and let them try again. Once they enter a valid day, exit the loop.

Here's the updated full code with these changes:

import java.util.Scanner;
import java.util.HashSet;
import java.util.Set;

public class DayValidator {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        // Fixed the typo and cleaned up the valid days array
        String[] validDays = {"Monday", "Thursday", "Wednesday", "Friday", "Saturday", "Sunday"};
        // Convert array to Set for easy contains check
        Set<String> validDaySet = new HashSet<>();
        for (String day : validDays) {
            validDaySet.add(day);
        }

        String inputDay;
        boolean isValid = false;

        do {
            System.out.println("Enter a day:\n Eg: Monday or Thursday");
            inputDay = keyboard.next();
            
            // Check if input is in the valid set
            if (validDaySet.contains(inputDay)) {
                isValid = true;
                System.out.println("Great, " + inputDay + " is a valid day!");
            } else {
                System.out.println("Oops, that's not a valid day. Please try again.");
            }
        } while (!isValid);

        keyboard.close();
        // You can add more logic here using the valid inputDay variable
    }
}

A couple of extra tips to make this more robust:

  • Case insensitivity: If you want to accept inputs like "monday" or "MONDAY", convert both the input and valid days to lowercase (or uppercase) before checking. For example:
    // When populating the set
    validDaySet.add(day.toLowerCase());
    // When checking input
    if (validDaySet.contains(inputDay.trim().toLowerCase())) {
        // ...
    }
    
  • Handle whitespace: Use inputDay.trim() to remove accidental leading/trailing spaces from the user's input before validation.

That should do the trick! 🚀

内容的提问来源于stack exchange,提问作者Gery .Z

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:41:47