Ask Question

Write a function that takes as input an English sentence (a string) and prints the total number of vowels and the total number of consonants in the sentence. The function returns nothing. Note that the sentence could have special characters like dots, dashes, and so on.

+2
Answers (1)
  1. 17 July, 02:55
    0
    public static void vowelCount (String word) {

    int vowelCount = 0;

    int consonantCount = 0;

    int wordLen = word. length ();

    //a, e, i, o, u

    for (int i=0; i
    if (word. charAt (i) = ='a'||word. charAt (i) = ='e'||word. charAt (i) = ='i'

    ||word. charAt (i) = ='o'||word. charAt (i) = ='u') {

    vowelCount++;

    }

    }

    System. out. println ("Number of Vowels: "+vowelCount);

    System. out. println ("Number of Consonants: " + (wordLen-vowelCount));

    }

    Explanation:

    The method vowelCount is implemented in Java

    Receives a string as argument

    Uses a for loop to iterate the entire string

    Uses an if statement to check for vowels

    Substract total vowels from the length of the string to get the consonants

    See complete code with a main method below:

    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 word = in. nextLine ();

    //Removing all special characters and whitespaces

    String cleanWord = word. replaceAll ("[^a-zA-Z0-9]", "");

    //Calling the Method

    vowelCount (cleanWord);

    }

    //The method

    public static void vowelCount (String word) {

    int vowelCount = 0;

    int consonantCount = 0;

    int wordLen = word. length ();

    //a, e, i, o, u

    for (int i=0; i
    if (word. charAt (i) = ='a'||word. charAt (i) = ='e'||word. charAt (i) = ='i'

    ||word. charAt (i) = ='o'||word. charAt (i) = ='u') {

    vowelCount++;

    }

    }

    System. out. println ("Number of Vowels: "+vowelCount);

    System. out. println ("Number of Consonants: " + (wordLen-vowelCount));

    }

    }
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a function that takes as input an English sentence (a string) and prints the total number of vowels and the total number of ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers