Java 程序用于计算句子中元音和辅音的数量
javaobject oriented programmingprogramming更新于 2024/4/12 13:00:17
在本文中,我们将了解如何计算 Java 中的元音和辅音。包括 'a' 'e' 'i' 'o' 'u' 的字母表被称为元音,所有其他字母都被称为辅音。
下面是相同的演示 −
输入
假设我们的输入是 −
你好,我叫 Charlie
输出
所需的输出将是 −
语句中的元音数量为:8 辅音中的元音数量为:12
算法
步骤 1- 开始 步骤 2- 声明两个整数:vowels_count、consonants_count 和一个字符串 my_str 步骤 3- 提示用户输入一个字符串值/定义字符串 步骤 4- 阅读值 步骤 5- 运行 for 循环,检查每个字母是辅音还是元音。增加 相应的整数。存储值。 步骤 6- 显示结果 步骤 7- 停止
示例 1
import java.util.Scanner;
public class VowelAndConsonents {
public static void main(String[] args) {
int vowels_count, consonants_count;
String my_str;
vowels_count = 0;
consonants_count = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("A scanner object has been defined ");
System.out.print("Enter a statement: ");
my_str = scanner.nextLine();
my_str = my_str.toLowerCase();
for (int i = 0; i < my_str.length(); ++i) {
char ch = my_str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
++vowels_count;
}
else
if ((ch >= 'a' && ch <= 'z')) {
++consonants_count;
}
}
System.out.println("The number of vowels in the statement is: " + vowels_count);
System.out.println("The number of vowels in the Consonants is: " + consonants_count);
}
}
输出
A scanner object has been defined Enter a statement: Hello, my name is Charlie The number of vowels in the statement is: 8 The number of vowels in the Consonants is: 12
示例 2
这里,整数已经被预先定义,并且它的值被访问并显示在控制台上。
public class VowelAndConsonents {
public static void main(String[] args) {
int vowels_count, consonants_count;
vowels_count = 0;
consonants_count = 0;
String my_str = "Hello, my name is Charie";
System.out.println("The statement is defined as : " +my_str );
my_str = my_str.toLowerCase();
for (int i = 0; i < my_str.length(); ++i) {
char ch = my_str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
++vowels_count;
}
else
if ((ch >= 'a' && ch <= 'z')) {
++consonants_count;
}
}
System.out.println("The number of vowels in the statement is: " + vowels_count);
System.out.println("The number of vowels in the Consonants is: " + consonants_count);
}
}
输出
The statement is defined as : Hello, my name is Charie The number of vowels in the statement is: 8 The number of vowels in the Consonants is: 11
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

