Answer:
public static int consonantCount(String str){
int numOfConsonants =0;
int numOfVowels =0;
String word = str.toLowerCase();
for(int i=0; i< word.length(); i++){
if(word.charAt(i)=='a'||word.charAt(i)=='i'||word.charAt(i)=='o'
||word.charAt(i)=='e'||word.charAt(i)=='u'||word.charAt(i)=='y'){
numOfVowels++;
}
}
numOfConsonants = (word.length()-numOfVowels);
return numOfConsonants;
}
Explanation:
Using Java programming Language
- Create two variables int numOfConsonants and int numOfVowels To hold the number of consonants and vowels repectively
- The english vowels for this question includes y or Y
- Convert the string entered into all lower case letters using java's toLowerCase method
- Using a for loop count the total number of vowels in the string
- Subtract the number of vowels in the string from the length of the string to get the number of consonants
- return the number of consonants
- Consider a complete program below where a user is prompted to enter a string, the string is stored in a variable, the string is cleaned (Removing all special characters and whitespaces)
- The method cosonantCount is then called
<em>import java.util.Scanner;</em>
<em>public class num2 {</em>
<em> public static void main(String[] args) {</em>
<em> Scanner in = new Scanner(System.in);</em>
<em> System.out.println("Enter a String");</em>
<em> String a = in.nextLine();</em>
<em> String cleanText = a.replaceAll("[^a-zA-Z0-9]", "");</em>
<em> System.out.println("The number of consonants in the word are "+consonantCount(cleanText));</em>
<em> }</em>
<em> public static int consonantCount(String str){</em>
<em> int numOfConsonants =0;</em>
<em> int numOfVowels =0;</em>
<em> String word = str.toLowerCase();</em>
<em> for(int i=0; i< word.length(); i++){</em>
<em> if(word.charAt(i)=='a'||word.charAt(i)=='i'||word.charAt(i)=='o'</em>
<em> ||word.charAt(i)=='e'||word.charAt(i)=='u'||word.charAt(i)=='y'){</em>
<em> numOfVowels++;</em>
<em> }</em>
<em> }</em>
<em> numOfConsonants = (word.length()-numOfVowels);</em>
<em> return numOfConsonants;</em>
<em> }</em>
<em>}</em>