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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP