English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à utiliser if en Java pour calculer le nombre de voyelles, de consonnes, de chiffres et d'espaces dans une phrase donnée.
public class Count { public static void main(String[] args) { String line = "Ce site web est";3som3."; 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 == " ") { ++espaces; } } System.out.println("Les voyelles : " + vowels); System.out.println("辅音: " + consonants); System.out.println("数字: " + digits); System.out.println("空格: " + spaces); } }
When the program is run, the output is:
vowel: 6 consonant: 11 number: 3 space: 3
In the above example, each check has4condition.
The first if condition is to check if the character isvowel.
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 into9between.
Finally, the last condition is to check if the character isspacecharacter.
For this, we use toLowerCase() to make the line lowercase. This is an optimization that does not check uppercase A to Z and vowels.
We use the length() function to know the length of the string, and use the charAt() function to get the character at the given index (position).