Java程序计算句子中元音和辅音的个数
在本文中,我们将了解如何在Java中计算元音和辅音的个数。包括'a' 'e' 'i' 'o' 'u'的字母称为元音,所有其他字母称为辅音。
下面是演示:
输入
假设我们的输入是:
Hello, my name is Charlie
输出
期望的输出将是:
The number of vowels in the statement is: 8 The number of vowels in the Consonants is: 12
算法
Step1- Start Step 2- Declare two integers: vowels_count, consonants_count and a string my_str Step 3- Prompt the user to enter a string value/ define the string Step 4- Read the values Step 5- Run a for-loop, check each letter whether it is a consonant or an vowel. Increment the respective integer. Store the value. Step 6- Display the result Step 7- Stop
示例 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
广告