Program opened below. You can scroll through the algorithm, Java code and output.
Program 14
Recursive Character Classification
Question
Design class Count to read a string without digits and recursively count vowels, consonants, spaces and special characters.
Algorithm
Step 1: Start and create a Count object.
Step 2: Initialize the stored text and all four counters.
Step 3: Read a complete input line.
Step 4: Scan it once for digits before recursive counting.
Step 5: If any digit is present, display an error and stop.
Step 6: Call Count_Char with the original string and position zero.
Step 7: In the recursive function, stop when the position reaches the string length.
Step 8: Read the character at the current position.
Step 9: Convert the character to uppercase for alphabet testing.
Step 10: If it is a letter, distinguish vowels from consonants.
Step 11: Increase the appropriate letter counter.
Step 12: If it is a space, increase the space counter.
Step 13: Otherwise increase the special-character counter.
Step 14: Call Count_Char for the next position.
Step 15: Display all four counts and stop.
Java program
Javaimport java.util.*;
class Count {
String st;
int v, c, s, sp;
Count() {
st = "";
}
void input() {
Scanner sc = new Scanner(System.in);
st = sc.nextLine();
}
void Count_Char(String text, int pos) {
if (pos == text.length()) {
return;
}
char ch = Character.toUpperCase(text.charAt(pos));
if (ch >= '0' && ch <= '9') {
throw new IllegalArgumentException("Digits not allowed");
}
if (ch >= 'A' && ch <= 'Z') {
if ("AEIOU".indexOf(ch) >= 0) {
v++;
} else {
c++;
}
} else if (ch == ' ') {
s++;
} else {
sp++;
}
Count_Char(text, pos + 1);
}
public static void main(String[] args) {
Count ob = new Count();
ob.input();
for (int i = 0; i < ob.st.length(); i++) {
char ch = ob.st.charAt(i);
if (ch >= '0' && ch <= '9') {
System.out.println("Invalid: digit found");
return;
}
}
ob.Count_Char(ob.st, 0);
System.out.println("Vowels=" + ob.v + " Consonants=" + ob.c);
System.out.println("Spaces=" + ob.s + " Special=" + ob.sp);
}
}Sample output
Input: Hello!
Output: Vowels=2 Consonants=3 / Spaces=0 Special=1