Algorithm
-
Input:
- Prompt the user to enter a sentence.
- Read the input sentence and store it in a variable.
-
Initialize counters:
- Initialize two variables,
vowelCount
andconsonantCount
, to keep track of the number of vowels and consonants, respectively.
- Initialize two variables,
-
Convert to lowercase:
- Convert the input sentence to lowercase to make the counting case-insensitive.
-
Iterate through each character:
- Use a loop to iterate through each character in the sentence.
-
Check for vowels and consonants:
- Inside the loop, for each character:
- Check if the character is a vowel (a, e, i, o, u).
- If it is a vowel, increment the
vowelCount
. - If it is a consonant (not a vowel and not a space or punctuation), increment the
consonantCount
.
- Inside the loop, for each character:
-
Display the results:
- After the loop, display the counts of vowels and consonants.
Code Examples
#1 Code Example- Program to count vowels, consonants, digits, and spaces
Code -
Java Programming
class Main {
public static void main(String[] args) {
String line = "This website is aw3som3.";
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);
// check if character is any of a, e, i, o, u
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
++vowels;
}
// check if character is in between a to z
else if ((ch >= 'a' && ch < = 'z')) {
++consonants;
}
// check if character is in between 0 to 9
else if (ch >= '0' && ch <= '9') {
++digits;
}
// check if character is a white space
else if (ch == ' ') {
++spaces;
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Digits: " + digits);
System.out.println("White spaces: " + spaces);
}
}
Copy The Code &
Try With Live Editor
Output
Vowels: 7
Consonants: 11
Digits: 2
White spaces: 3
Consonants: 11
Digits: 2
White spaces: 3
Demonstration
Java Programing Example to Count the Number of Vowels and Consonants in a Sentence-DevsEnv