指出哪个元音在字符串中出现次数最多

Indicate which vowel occurs the most in a string

我正在 Java 中编写一个程序,它应该提供如下输出:

我的代码可以编译,除了确定哪个元音出现次数最多之外,我的所有事情都成功了。

我不确定我应该做什么,首先计算单个元音(例如 "a")出现了多少次(而不是字符串中出现了多少个元音)。在找到每个元音的总和后,我不确定用什么来确定具有最大值的元音。一旦我能够完成这两个步骤,我就不确定如何正确输出。我更愿意使用 if 语句来完成此操作,但是我不知道这是否可能。

任何 help/tips 将不胜感激,这是我编写的代码:

    // which vowel occurs the most
    if (ch == 'a')
      vowelA++;
    else if (ch == 'e')
      vowelE++;
    else if (ch == 'i')
      vowelI++;
    else if (ch == 'o')
      vowelO++;
    else if (ch == 'u')
      vowelU++;

    if (vowelA > vowelE && vowelA > vowelI && vowelA > vowelO && vowelA > vowelU)
    {
      maxVowels = vowelA;
    }
  }

// OUTPUT
System.out.println("vowel" + " " + "occurs the most = " + maxVowels);

 }
}

可以有很多种方法。我正在写其中一个。你可以试试看:

// for number of VOWELS
for (int i = 0; i < str.length(); i++)
{
    ch = str.charAt(i);
    ch = Character.toLowerCase(ch);

    // is this a vowel
    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
    {
        vowels++;
    }

    // which vowel occurs the most
    if (ch == 'a')
        vowelA++;
    else if (ch == 'e')
        vowelE++;
    else if (ch == 'i')
        vowelI++;
    else if (ch == 'o')
        vowelO++;
    else if (ch == 'u')
        vowelU++;

}

maxVowels = Math.max(vowelA, Math.max(vowelE, Math.max(vowelI, Math.max(vowelO, vowelU))));

输出:

注意:我刚刚在大写逻辑之前添加了 maxVowels = Math.max(vowelA, Math.max(vowelE, Math.max(vowelI, Math.max(vowelO, vowelU))));,并删除了存储 maxVowels 值的 if 条件。

另一种方式:maxVowels = Math.max(vowelA, Math.max(vowelE, Math.max(vowelI, Math.max(vowelO, vowelU))));替换为Collections.max(Arrays.asList(vowelA, vowelE, vowelI, vowelO, vowelU));

试试这个代码:

{
   public static void main (String []args)
 {
    Scanner scan = new Scanner(System.in);
    String str = scan.nextLine();

    int vowels = 0, digits = 0, spaces = 0, upper = 0;
    String line = str;
    int max_vowel_count = 0;
    for(int i = 0; i < line.length(); ++i)
    {
        char ch = line.charAt(i);
        if(ch == 'a' || ch == 'e' || ch == 'i'
            || ch == 'o' || ch == 'u') {


            int a_count = line.length() - line.replace("a", "").length();
            int e_count = line.length() - line.replace("e", "").length();
            int i_count = line.length() - line.replace("i", "").length();
            int o_count = line.length() - line.replace("o", "").length();
            int u_count = line.length() - line.replace("u", "").length();

            max_vowel_count = Math.max(a_count, Math.max(e_count, Math.max(i_count, Math.max(o_count, u_count))));

            ++vowels;
        }
        else if( ch >= '0' && ch <= '9')
        {
            ++digits;
        }
        else if (ch >= 'A' && ch <= 'Z'){ 
            ++upper; 
        }
        else if (ch ==' ')
        {
            ++spaces;
        }
    }

    System.out.println("Vowels: " + vowels);
    System.out.println("Digits: " + digits);
    System.out.println("Upper Case: " + upper);
    System.out.println("White spaces: " + spaces);
    System.out.println("Max Vowel Count "+ max_vowel_count);

}

如果您对基于流的解决方案感兴趣:


    public static void main(String[] args) {

        String input = "This String has vowels and 12345 digits";

        Map<String, Integer> counts = input.chars()
                .mapToObj((str) -> charTypes(str))
                .flatMap((it) -> it)
                .collect(Collectors.toMap(Function.identity(), v -> 1, Integer::sum));

        System.out.println("Vowels: " + counts.getOrDefault("vowel", 0));
        System.out.println("Upper Case: " + counts.getOrDefault("upper", 0));
        System.out.println("Digits: " + counts.getOrDefault("digit", 0));
        System.out.println("White spaces: " + counts.getOrDefault("whitespace", 0));

        Optional<Map.Entry<String, Integer>> maxVowels = counts.entrySet()
                .stream()
                .filter((str) -> str.getKey().length() == 1)
                .filter((str) -> vowels.contains((int)str.getKey().charAt(0)))
                .max(Comparator.comparingInt(Map.Entry::getValue));

        if (maxVowels.isPresent()) {
            System.out.println("Max Vowel was " + maxVowels.get().getKey() + " with  " + maxVowels.get().getValue() + " occurrences");
        } else {
            System.out.println("No vowels found");
        }
    }

    private static Set<Integer> vowels = Set.of((int) 'a', (int) 'e', (int) 'i', (int) 'o', (int) 'u');

    public static boolean isVowel(int c) {
        return vowels.contains(Character.toLowerCase(c));
    }

    public static Stream<String> charTypes(int c) {
        List<String> types = new ArrayList<>();

        if (isVowel(c)){
            types.add("vowel");
            types.add(String.valueOf((char)c));
        }

        if (Character.isWhitespace(c)) {
            types.add("whitespace");
        }

        if (Character.isDigit(c)) {
            types.add("digit");
        }

        if (Character.isUpperCase(c)) {
            types.add("upper");
        }

        return types.stream();
    }

(将元音类型设为枚举会有所改进)