Ask Question
18 October, 04:31

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.

+5
Answers (1)
  1. 18 October, 08:00
    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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers