Ask Question

Write a program with functions that accepts a string as an argument and returns the number of vowels that the string contains. The application should have another function that accepts a string as an argument and return the number of consonants that the string contains. The application should let the user enter a string and should display the number of vowels and the number of consonants it contains.

+4
Answers (1)
  1. 29 January, 19:50
    0
    import java. util. Scanner;

    public class num11 {

    public static void main (String[] args) {

    Scanner in = new Scanner (System. in);

    System. out. println ("Enter a word or phrase");

    String word = in. nextLine ();

    //Calling the methods

    System. out. println ("Total vowels in "+word+" are "+numVowels (word));

    System. out. println ("Total consonants in "+word+" are "+numConsonants (word));

    }

    public static int numVowels (String word) {

    //Remove spaces and convert to lowercase

    //Assume that only correct character a-z are entered

    String newWord = word. toLowerCase (). replaceAll (" ","");

    int vowelCount = 0;

    for (int i = 0; i < = newWord. length () - 1; i++) {

    if (newWord. charAt (i) = ='a'||newWord. charAt (i) = ='e'||newWord. charAt (i) = ='i'

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

    vowelCount++;

    }

    }

    return vowelCount;

    }

    public static int numConsonants (String word) {

    //Remove spaces and convert to lowercase

    //Assume that only correct character a-z are entered

    String newWord = word. toLowerCase (). replaceAll (" ","");

    int consonantCount = 0;

    //Substract total vowels from the length of the word to get the consonants

    consonantCount = newWord. length () - numVowels (word);

    return consonantCount;

    }

    }

    Explanation:

    Create two methods vowelCount () and consonantCount () both accepts a string parameter and returns an int vowelCount () Uses a for loop to count the occurrence of the vowels (a, e, i, o, u) in the string and returns the count. consonantCount calls vowelCount and subtracts the vowelCount from the string length In the main Method the user is prompted to enter a string The two methods are called to return the number of vowels and consonants Observe also that it is assumed that user entered only strings containing the character a-Z. Observe also that the string is converted to all lower cases and whitespaces removed.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a program with functions that accepts a string as an argument and returns the number of vowels that the string contains. The ...” 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