Java vowel consonant space counts switch?
// Prints out the number of vowels, consonants, and space
characters in str.
static void printCounts(final String str) {
// Keep track of totals
int numVowels = 0;
int numConsonants = 0;
int numSpaces = 0;
// All lowercase chars will simplify the check for letters.
final String strLower = str.toLowerCase();
for (final char ch : strLower.toCharArray()) {
// Switch on the type of character of ch and update the correct
total
switch (getType(ch)) {
case VOWEL:
++numVowels;
break;
case CONSONANT:
++numConsonants;
break;
case SPACE:
++numSpaces;
break;
}
}
// Done
System.out.println("Vowels:\t" + numVowels);
System.out.println("Consonants:\t" + numConsonants);
System.out.println("Spaces:\t" + numSpaces);
}
private enum CharType {VOWEL, CONSONANT, SPACE, OTHER;}
// Returns the CharType of ch
static CharType getType(final char ch) {
if (ch >= 'a' && ch <= 'z') { // letters
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return CharType.VOWEL;
default:
return CharType.CONSONANT;
}
} else if (ch == ' ') { // spaces
return CharType.SPACE;
}
return CharType.OTHER;
}