Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java program to count the no. of vowels and consonants in a given string

VowelConsonantCounter.java

import java.util.Scanner;
public class VowelConsonantCounter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a string:");
        String input = scanner.nextLine();

        int vowelCount = 0, consonantCount = 0;

        // Convert the string to lowercase to make the checks case-insensitive
        input = input.toLowerCase();

        // Loop through each character in the string
        for (char c : input.toCharArray()) {
            if (c >= 'a' && c <= 'z') { // Check if the character is a letter
                if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
                    vowelCount++;
                } else {
                    consonantCount++;
                }
            }
        }

        System.out.println("Number of vowels: " + vowelCount);
        System.out.println("Number of consonants: " + consonantCount);

        //scanner.close();
    }
}

Explanation:

    1. Input Handling:

    • • The program takes a string input from the user.
    • • Converts the string to lowercase to simplify vowel/consonant checks.

    2. Character Analysis:

    • • It loops through each character in the string.
    • • Checks if the character is a letter (a-z or A-Z).
    • • Determines whether the letter is a vowel (a, e, i, o, u) or a consonant.

    3. Output:

    • • o Counts and displays the number of vowels and consonants.

Output

Input:
Enter a string:
Silan Software
Output:
Number of vowels: 5
Number of consonants: 8

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext