ในบทความนี้ เราจะเรียนรู้วิธีนับจำนวนสระ (vowels) และพยัญชนะ (consonants) ในประโยคภาษาอังกฤษใน Java สระคือ a, e, i, o, u ส่วนตัวอักษรอื่นๆ เป็นพยัญชนะ
ตัวอย่างการทำงาน
อินพุต:
Hello, my name is Charlie
เอาต์พุต:
The number of vowels in the statement is: 8 The number of consonants in the statement is: 12
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวนับ:
vowels_count,consonants_countและสตริงmy_str - รับค่าสตริงจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- แปลงสตริงเป็นตัวเล็กทั้งหมดด้วย
toLowerCase() - วนลูป
forตรวจสอบแต่ละตัวอักษร: ถ้าเป็นสระ เพิ่ม vowels_count, ถ้าเป็นตัวอักษร a-z เพิ่ม consonants_count - แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class VowelAndConsonants {
public static void main(String[] args) {
int vowels_count = 0, consonants_count = 0;
String my_str;
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 consonants in the statement is: " + consonants_count);
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class VowelAndConsonants {
public static void main(String[] args) {
int vowels_count = 0, consonants_count = 0;
String my_str = "Hello, my name is Charlie";
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 consonants in the statement is: " + consonants_count);
}
}
หมายเหตุ: โค้ดนับเฉพาะตัวอักษรอังกฤษ a-z ไม่นับตัวเลข ช่องว่าง หรือสัญลักษณ์พิเศษ