java

Program to Count the Number of Vowels and Consonants in a Given String in Java

In this tutorial, we are going to see how to write a program that counts the number of vowels and consonants in a given string in Java.

In the following example, we have two variables “vowel” and “cons” to store the number of vowels and consonants respectively. We converted each character in the string to lowercase using the toLowerCase() method for easy comparison.

Then correspond each character in the string to the vowels “a”, “e”, “i”, “o”, “u” using the charAt() method and the if..else..if declaration if one correspondence is found then we increment the vowel counter “vowel” otherwise we increment the consonant counter “cons”.
 
[st_adsense]  

Program to Count the Number of Vowels and Consonants in a Given String in Java
public class Main {

    public static void main(String[] args) {
        String text = "StackHowTo";
        int voyel = 0, cons = 0;

        //Convert all characters to lowercase
        text = text.toLowerCase();
        for(int i = 0; i < text.length(); i++) {
           char c = text.charAt(i); 
           if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { 
                voyel++;
           } else if((c >= 'a' && c <= 'z')) {
                cons++;
           }
        }
        System.out.println("Number of vowels: " + voyel);
        System.out.println("Number of consonants: " + cons);
    }
}

Output:

Number of vowels: 3
Number of consonants: 7
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *