Program opened below. You can scroll through the algorithm, Java code and output.
Program 80
Count Vowels and Consonants in Each Word
Question
Accept an upper-case sentence ending with ., ? or !. Count and display the number of vowels and consonants in each word.
Algorithm
Step 1: Start.
Step 2: Input and validate the sentence.
Step 3: Remove its final punctuation and split into words.
Step 4: For each word, initialize vowelCount and consonantCount to zero.
Step 5: Examine each character of the word.
Step 6: If it is A, E, I, O or U, increment vowelCount; otherwise increment consonantCount.
Step 7: Store the computed result and prepare it for display.
Step 8: Store the computed result and prepare it for display.
Step 9: Store the computed result and prepare it for display.
Step 10: Display each word with its two counts.
Step 11: Stop.
Java program
Javaimport java.util.*;
class WordVowelsConsonants {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine().trim();
if (!s.matches("[A-Z]+( [A-Z]+)*[.?!]")) {
System.out.println("INVALID INPUT");
return;
}
String[] words = s.substring(0, s.length() - 1).split(" ");
for (String w : words) {
int v = 0, c = 0;
for (char ch : w.toCharArray()) {
if ("AEIOU".indexOf(ch) >= 0) {
v++;
}
else {
c++;
}
}
System.out.println(w + ": VOWELS = " + v + ", CONSONANTS = " + c);
}
}
}Sample output
Input: HELLO WORLD!
Output:
HELLO: VOWELS = 2, CONSONANTS = 3
WORLD: VOWELS = 1, CONSONANTS = 4