Java Program to count Vowels and Consonants in a given string

Program

import java.util.Scanner;
public class CountVowelsAndConsonantsInString {
    public void countVowelConsonants(String inputStr)
    {
        int vowelCount = 0;
        int consonantCount = 0;
        inputStr = inputStr.toLowerCase();
        for(int i = 0; i < inputStr.length(); i++) {    
            //check for vowel  (a, e, i, o, u) 
            if(inputStr.charAt(i) == 'a' || inputStr.charAt(i) == 'e' || inputStr.charAt(i) == 'i' || inputStr.charAt(i) == 'o' || inputStr.charAt(i) == 'u') {    
               // Increment vowel count  
               vowelCount++;    
            }    
            //Checks for consonant    
            else if(inputStr.charAt(i) >= 'a' && inputStr.charAt(i)<='z') {      
                //Increment consonant count   
                consonantCount++;    
            }              
        }
        System.out.println("Number of vowels: "+ vowelCount); 
        System.out.println("Number of consonants: "+ consonantCount);
    }
    public static void main(String[] args)
    {
        CountVowelsAndConsonantsInString countVowelsAndConsonantsInString = new CountVowelsAndConsonantsInString();
        Scanner reader = new Scanner(System.in);
        System.out.print("Enter the String: ");
        String inputString = reader.nextLine();
        countVowelsAndConsonantsInString.countVowelConsonants(inputString);
    }
}

This program counts the number of vowels and consonants in a given string by iterating through each character and classifying it.

  1. Input:

    • The program uses the Scanner class to accept a string from the user.
  2. Initialization:

    • Two counters are initialized: vowelCount and consonantCount to track the number of vowels and consonants.
  3. String Conversion:

    • The input string is converted to lowercase using toLowerCase() to handle case-insensitive comparisons.
  4. Iteration Through Characters:

    • A for loop iterates through each character of the string:
      • Vowel Check:
        • The character is checked against vowels (a, e, i, o, u).
        • If it matches, vowelCount is incremented.
      • Consonant Check:
        • The character is checked to see if it's between 'a' and 'z' (indicating a letter).
        • If it's not a vowel, it's counted as a consonant, and consonantCount is incremented.
  5. Output:

    • The program prints the counts of vowels and consonants.

Key Features:

  • Character Classification:
    • Differentiates between vowels and consonants.
  • Lowercase Conversion:
    • Ensures uniformity when checking characters.
  • Efficiency:
    • Uses a single loop to process the string.

Output

$ javac CountVowelsAndConsonantsInString.java
$ java CountVowelsAndConsonantsInString
Enter the String: oodlescoop
Number of vowels: 5
Number of consonants: 5