105k views
2 votes
consonantCount (s2) Write the function consonantCountthat counts how many times a consonant (either lowercase or uppercase) occurs in a string. It takes a string sas input and returnsan integer, the number of consonants in the string. For this question, yand Yare not consonants. Please use a for loop to do the computation. Please do not use a brute force solution (comparing against one consonant at a time): it will not receive credit.

1 Answer

0 votes

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;

}

Step-by-step 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;

}

}

User Mortenstarck
by
6.8k points