Respuesta :
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
import java.util.Scanner;
public class num2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String a = in.nextLine();
String cleanText = a.replaceAll("[^a-zA-Z0-9]", "");
System.out.println("The number of consonants in the word are "+consonantCount(cleanText));
}
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;
}
}