การนับจำนวนพยัญชนะและสระในข้อความ
โจทย์
Write a program that reads a string entered by the user. The program should then analyze the string to count the number of vowels (specifically the letters A, E, I, O, and U) and consonants present. Finally, the program should display the counts of both vowels and consonants.
| Input | Output |
|---|---|
| hello | Vowels: 2 Consonants: 3 |
โค้ด
import java.util.*;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine().toLowerCase();
int vowelCount = 0;
int consonantCount = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (Character.isLetter(c)) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowelCount++;
break;
default:
consonantCount++;
}
}
}
System.out.println("Vowels: " + vowelCount);
System.out.println("Consonants: " + consonantCount);
}
}คำอธิบาย
ปรับปรุงล่าสุด