Java 程序:计算句子中元音和辅音的数量

要理解此示例,您应了解以下Java编程主题


示例:统计元音字母、辅音字母、数字和空格的程序

class Main {

  public static void main(String[] args) {
    String line = "This website is aw3som3.";
    int vowels = 0, consonants = 0, digits = 0, spaces = 0;

    line = line.toLowerCase();
    for (int i = 0; i < line.length(); ++i) {
      char ch = line.charAt(i);

      // check if character is any of a, e, i, o, u
      if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
        ++vowels;
      }

      // check if character is in between a to z
      else if ((ch >= 'a' && ch <= 'z')) {
        ++consonants;
      }
      
      // check if character is in between 0 to 9
      else if (ch >= '0' && ch <= '9') {
        ++digits;
      }
      
      // check if character is a white space
      else if (ch == ' ') {
        ++spaces;
      }
    }

    System.out.println("Vowels: " + vowels);
    System.out.println("Consonants: " + consonants);
    System.out.println("Digits: " + digits);
    System.out.println("White spaces: " + spaces);
  }
}

输出

Vowels: 7
Consonants: 11
Digits: 2
White spaces: 3

在上面的示例中,我们有 4 个条件用于每个检查。

  • 第一个 if 条件用于检查字符是否为元音字母
  • if 后面的 else if 条件用于检查字符是否为辅音字母。仅当 if 条件为 false 时才检查此条件。
  • 第二个 else if 用于检查字符是否在0 到 9 之间。
  • 最后,最后一个条件用于检查字符是否为空字符。

为此,我们已使用 toLowerCase() 将该行转换为小写。这是一项优化,用于避免检查大写 A 到 Z 和元音字母。

我们使用了 length() 函数来获取字符串的长度,并使用 charAt() 来获取给定索引(位置)处的字符。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战