English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
في هذا البرنامج، ستتعلم كيفية استخدام if في Java لحساب عدد الصوتيات، الحروف الصوتية، الأرقام والفراغات في جملة معينة.
public class Count { public static void main(String[] args) { String line = "هذا الموقع هو رائع."; int vowels = 0, consonants = 0, digits = 0, spaces = 0; line = line.toLowerCase(); for (int i = 0; i < line.length(); ++i) { char ch = line.charAt(i); if (ch == 'a' || ch == 'e' || ch == 'i') || ch == 'o' || ch == 'u') { ++vowels; } else if ((ch >= 'a' && ch <= 'z')) { ++consonants; } else if (ch >= '0' && ch <= '9') { ++digits; } else if (ch == ' ') { ++spaces; } } System.out.println("الصوتيات: " + vowels); System.out.println("Consonants: " + consonants); System.out.println("Numbers: " + digits); System.out.println("Spaces: " + spaces); } }
When running the program, the output is:
Vowels: 6 Consonants: 11 Numbers: 3 Spaces: 3
In the above example, each check has 4 conditions.
The first if condition is to check if the character isVowels.
The else if condition after if is used to check if the character is a consonant. The order should be the same, otherwise, all the vowels are also considered as consonants.
The third condition (else if) is to check if the character is in0 to 9between.
Finally, the last condition is to check if the character isSpacesCharacters.
For this, we use toLowerCase() to make the line lowercase. This is an optimization that does not check uppercase A to Z and vowels.
To know the length of the string, we use the length() function, and to get the character at a given index (position), we use the charAt() function.