如何在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:
- Use a loop to repeat input until valid: A
do-whileloop is perfect here because we want to prompt the user at least once, then keep asking until they enter a valid day. - 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
Setfor faster, cleaner lookups. - 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
相关产品推荐
相关产品推荐

