Trong bài viết này, chúng ta sẽ tìm hiểu cách đếm nguyên âm và phụ âm trong Java. Các chữ cái 'a', 'e', 'i', 'o', 'u' gọi là nguyên âm, các chữ cái còn lại là phụ âm.
Dưới đây là minh họa:
Đầu vào
Giả sử đầu vào:
Hello, my name is Charlie
Đầu ra
Kết quả mong đợi:
Số nguyên âm trong câu: 8 Số phụ âm trong câu: 12
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo hai số nguyên: vowels_count, consonants_count và chuỗi my_str Bước 3 - Nhập chuỗi từ người dùng hoặc định nghĩa trước Bước 4 - Đọc giá trị Bước 5 - Chạy vòng lặp for, kiểm tra từng ký tự là nguyên âm hay phụ âm. Tăng biến đếm tương ứng. Lưu giá trị. Bước 6 - Hiển thị kết quả Bước 7 - DỪNG
Ví dụ 1: Nhập từ bàn phím
Người dùng nhập câu dựa trên lời nhắc. Thử trực tiếp trong coding ground.
import java.util.Scanner;
public class VowelAndConsonants {
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 consonants in the statement is: " + consonants_count);
}
}
Đầu ra
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 consonants in the statement is: 12
Ví dụ 2: Chuỗi định nghĩa trước
Chuỗi đã được định nghĩa trước, giá trị được truy xuất và hiển thị.
public class VowelAndConsonants {
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 consonants in the statement is: " + consonants_count);
}
}
Đầu ra
The statement is defined as: Hello, my name is Charie The number of vowels in the statement is: 8 The number of consonants in the statement is: 11