How can I check how many consonants and vowels there are in a sentence in Java?
char, java, loops
Solution
Use `Character.isLetter(ch)` to determine if the character is a vowel or a consonant, then check to see if the character in question is in the set of vowels.
One way to create the set of vowels:
Set<Character> vowels = new HashSet<Character>();
for (char ch : "aeiou".toCharArray()) {
vowels.add(ch);
}
And to increment `v` or `c`:
if (Character.isLetter(a)) {
if (vowels.contains(Character.toLowerCase(a))) {
v++;
} else {
c++;
}
}
Problem
At the end of my loop, I am planning on displaying the number of consonants and vowels in the sentence. I was wondering if there was a more efficient way to check how many consonants and vowels are in a given sentence, rather than using an if statement and manually inputting every letter. (key refers to my Scanner which has already been initialized) Edit: It needs to ignore digits and other special characters, so for example if I write Hello@ how 1are you?. There should be 8 vowels and 6 consonants. ``` System.out.println("Please enter the sentence to analyze: "); String words = key.nextLine(); //the sentence the user inputs int c = 0; //# of consonants int v = 0; //# of vowels int length = words.length(); //length of sentence int check; //goes over each letter in our sentence for(check = 0; check < length; check++){ char a = words.charAt(check); if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o' || a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y') v = v + 1; else if(a == 'b' || a == 'B' || a == 'c' || a == 'C' || a == 'd' || a == 'D' || a == 'f' || a == 'F' || a == 'g' || a == 'G' || a == 'h' || a == 'H' || a == 'j' || a == 'J' || a == 'k' || a == 'K' || a == 'l' || a == 'L' || a == 'm' || a == 'M' || a == 'n' || a == 'N' || a == 'p' || a == 'P' || a == 'q' || a == 'Q' || a == 'r' || a == 'r' || a == 's' || a == 'S' || a == 't' || a == 'T' || a == 'v' || a == 'V' || a == 'w' || a == 'W' || a == 'x' || a == 'X' || a == 'z' || a == 'Z') c = c + 1; } ```