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

Here we are explaining how to write a java program to count the number of vowels and consonants in a given string. So first we have to read a string from the user, convert it into uppercase and check each character of the string is a vowel or consonants. If the character is a vowel then we will increment the towel counter, otherwise, we will increment the consonants counter. Then we will display the vowel counter and consonant counter.

How to convert a string into lowercase in java?

We can convert the string into lowercase by using the String function toLowerCase() of the class String. An example is shown below

str="How Are You"
str = str.toLowerCase();
 

How to implement the java program to count the vowels and consonants in a string?

First, we have to declare the class CountVC with a public modifier. Then open the main() and read the string from the user into the variable str. Then set the two counter variables vc and cc to zero. Then convert the string into lowercase. By using a for loop convert each letter of the string into a character. And check whether the character is equal to a/e/i/o/u.If true then increment vc by one. Else increment cc by one. Then display the number of vowels in the string as vc and the number of consonants in the string as cc.

ALGORITHM

STEP 1: Declare the class CountVC as a public modifier.

STEP 2: Open the main() and read a string from the user into the variable str.

STEP 3: Set the counter variable vc and cc to zero.

STEP 4: Convert the string into lowercase using str.toLowerCase() function.

STEP 5: By using for loop with the condition i

STEP 6: Check the character is a or e or i or o or u, if true then increment vc else increment cc.

STEP 7: Increment i by one and repeat step 5.

STEP 8:Display the number of vowels in the string as vc and the number of consonants in the string as cc.

 

Java Source Code

                                          import java.util.Scanner;
public class CountVC {
    public static void main(String[] args) {

        Scanner sc1 = new Scanner(System.in);
        System.out.println("Enter the String :");
        String str = sc1.nextLine();
        
        int vc = 0, cc = 0;

        str = str.toLowerCase();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                vc++;
            } else if ((ch >= 'a' && ch <= 'z')) {
                cc++;
            }
        }
        System.out.println("Number of Vowels in the string: " + vc);
        System.out.println("Number of Consonants in the string: " + cc);
    }
}
                                      

OUTPUT

Enter the String :I am a girl
Number of Vowels in the string: 4
Number of Consonants in the string: 4