首页 > 解决方案 > 在 Java 中分别计算元音

问题描述

示例输出:

输入一个字符串:你好

字符串中每个元音的数量:

a: 0
e: 1
i: 0
o: 1
u: 0
other characters: 3
import java.util.Scanner;
public class Main {
  public static void main(String args[]) {
    int count = 0;
    System.out.println("Enter a string: ");
    Scanner myObject = new Scanner(System.in);
    String anyWord = myObject.nextLine();

    for (int i = 0; i < anyWord.length(); i++) {
      char vowelA = anyWord.charAt(i);
      if (vowelA == 'a' || vowelA == 'A') {
        count++;
      }
    }
    System.out.println("a: " + count);
  }
}

这是我正在编写的代码,但我不知道下一步该怎么做......需要你的帮助......

标签: java

解决方案


即使其他人有工作,我也会在这里添加我的解决方案。在我看来,为您正在寻找的每个独特项目创建一堆变量是不好的做法。如果您现在也想接受y作为元音怎么办?

这是我的解决方案,它使用一个字符数组来定义应该计算哪些字符。然后我们创建一个 Hashmap,其中键是字符,值是字符串中每个字符出现的计数。然后我们遍历字符串,如果键已经存在于 Hashtable 中,则增加 Hashtable 中的计数值。请记住,我们之前通过这样做准备了 Hashtable。最后,我们打印出所有键及其相关值。

import java.util.*;

public class Main {
    public static void main(String []args){
    
        // List of vowels.
        char vowel_characters[] = {'a', 'e', 'i', 'o', 'u'};
    
        // Add vowels to dictionary, assign value to zero.
        Hashtable vowels = new Hashtable();
        for (char vowel : vowel_characters) {
            vowels.put(vowel, 0);
        }
    
        // The input string.
        String input = "Hello, world!";
    
        // Check if the character at index `i` is in the dictionary, if so then
        //  add 1 to its counter.
        for (int i = 0; i < input.length(); i++) {
            char vowel = input.charAt(i);
            if (vowels.containsKey(vowel)) {
                vowels.put(vowel, (int)vowels.get(vowel) + 1);
            }
        }
    
        // Print the results/
        for (Object vowel : vowels.keySet()) {
            System.out.println((char)vowel + ": " + vowels.get(vowel)); 
        }
    }
}

推荐阅读