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

如何验证Java Scanner输入字符串包含至少两个元音?

Fixing Scanner Input Validation for Minimum Two Vowels

Got it, let's fix this together! Your current code is on the right track, but it's checking for at least one vowel-only token instead of verifying that the input string contains two or more vowels total. Let's break down the issue and adjust the code properly.

What's Wrong with the Original Code?

Your regex [aeiouAEIOU]+ matches a sequence of one or more vowels, but sc.hasNext(...) checks if the next token (split by whitespace) is exactly that sequence. So if someone enters "abcde" (which has two vowels), your code would still throw an error because the token isn't made up entirely of vowels. That's not what you want!

Solution 1: Count Vowels (Most Intuitive)

This approach explicitly counts how many vowels are in the input string, which is easy to read and modify if you need to adjust the vowel requirement later.

Scanner sc = new Scanner(System.in);
System.out.print("Input alphabetical character string: ");

while (true) {
    String input = sc.nextLine().trim();
    
    // Handle empty input
    if (input.isEmpty()) {
        System.out.println("Error: Please enter a non-empty string.");
        System.out.print("Try again: ");
        continue;
    }
    
    // Ensure input only contains alphabetical characters
    if (!input.matches("[a-zA-Z]+")) {
        System.out.println("Error: Please enter only alphabetical characters.");
        System.out.print("Try again: ");
        continue;
    }
    
    // Count total vowels in the input
    long vowelCount = input.chars()
                            .mapToObj(c -> (char) c)
                            .filter(c -> "aeiouAEIOU".indexOf(c) != -1)
                            .count();
    
    if (vowelCount >= 2) {
        System.out.println("Valid input!");
        break; // Exit loop once valid input is received
    } else {
        System.out.println("Error: Sequence requires a minimum of two vowels.");
        System.out.print("Try again: ");
    }
}

sc.close();

Solution 2: Use a Regex to Match At Least Two Vowels

If you prefer a regex-based approach, you can use a pattern that checks the entire string for at least two vowels (regardless of where they are):

Scanner sc = new Scanner(System.in);
System.out.print("Input alphabetical character string: ");

while (true) {
    String input = sc.nextLine().trim();
    
    if (input.isEmpty()) {
        System.out.println("Error: Please enter a non-empty string.");
        System.out.print("Try again: ");
        continue;
    }
    
    if (!input.matches("[a-zA-Z]+")) {
        System.out.println("Error: Please enter only alphabetical characters.");
        System.out.print("Try again: ");
        continue;
    }
    
    // Regex to check for at least two vowels (case-insensitive)
    if (input.matches("(?i).*[aeiou].*[aeiou].*")) {
        System.out.println("Valid input!");
        break;
    } else {
        System.out.println("Error: Sequence requires a minimum of two vowels.");
        System.out.print("Try again: ");
    }
}

sc.close();

Regex Breakdown:

  • (?i): Enables case-insensitive matching (so we don't have to write AEIOU separately)
  • .*: Matches any number of any characters (including zero)
  • [aeiou]: Matches a single vowel
  • The pattern .*[aeiou].*[aeiou].* ensures there are at least two vowels somewhere in the string.

Both solutions will correctly validate that the input string contains at least two vowels while also ensuring it's made up of only alphabetical characters (as your original prompt mentions).

内容的提问来源于stack exchange,提问作者Cruskits

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:25:13