Computer Science, asked by nikitashi88, 5 months ago

WAP in JAVA to creat a method find() that accepts a string and returns the number of consonants within it. Also create a main method to call the method find().​

Answers

Answered by kalivyasapalepu99
0

Java Program to count the total number of vowels and consonants in a string.

As we know that, the characters a, e, i, o, u are known as vowels in the English alphabet. Any character other than that is known as the consonant.

To solve this problem, First of all, we need to convert every upper-case character in the string to lower-case so that the comparisons can be done with the lower-case vowels only not upper-case vowels, i.e.(A, E, I, O, U). Then, we have to traverse the string using a for or while loop and match each character with all the vowels, i.e., a, e, i, o, u. If the match is found, increase the value of count by 1 otherwise continue with the normal flow of the program. The algorithm of the program is given below.

AlgorithmSTEP 1: STARTSTEP 2: SET vCount =0, cCount =0STEP 3: DEFINE string str = "This is a really simple sentence".STEP 4: CONVERT str to lowercaseSTEP 5: SET i =0.STEP 6: REPEAT STEP 6 to STEP 8 UNTIL i<str.length()STEP 7: IF any character of str matches with any vowel then

vCount = vCount + 1.

STEP 8: IF any character excepting vowels lies BETWEEN a and z then

cCount = cCount =+1.STEP 9: i = i + 1STEP 10: PRINT vCount.STEP 11: PRINT cCount.STEP 12: END

Program -

public class CountVowelConsonant {        public static void main(String[] args) {                        //Counter variable to store the count of vowels and consonant            int vCount = 0, cCount = 0;                        //Declare a string            String str = "This is a really simple sentence";                        //Converting entire string to lower case to reduce the comparisons            str = str.toLowerCase();                        for(int i = 0; i < str.length(); i++) {                //Checks whether a character is a vowel                if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {                    /quote /Increments the vowel counter                    vCount++;                }                //Checks whether a character is a consonant                else if(str.charAt(i) >= 'a' && str.charAt(i)<='z') {                      //Increments the consonant counter                    cCount++;                }            }            System.out.println("Number of vowels: " + vCount);            System.out.println("Number of consonants: " + cCount);        }    }   

Output:

Number of vowels: 10 Number of consonants: 17

Attachments:
Similar questions