Introduction
Counting the number of vowels and consonants in a string is a common task in text processing. This exercise helps you understand string manipulation and the use of loops and conditionals in Java. This guide will walk you through writing a Java program that counts the number of vowels and consonants in a given string.
Problem Statement
Create a Java program that:
- Prompts the user to enter a string.
- Counts the number of vowels in the string.
- Counts the number of consonants in the string.
- Displays the counts for both vowels and consonants.
Example:
- Input: "Hello World"
- Output:
Number of vowels: 3 Number of consonants: 7
Solution Steps
- Read the String: Use the Scannerclass to take the string as input from the user.
- Initialize Counters: Create variables to store the count of vowels and consonants.
- Iterate Through the String: Loop through each character in the string and check if it is a vowel or a consonant.
- Display the Counts: Print the counts of vowels and consonants.
Java Program
// Java Program to Count Vowels and Consonants in a String
// Author: https://www.rameshfadatare.com/
import java.util.Scanner;
public class VowelConsonantCounter {
    public static void main(String[] args) {
        // Step 1: Read the string from the user
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter a string: ");
            String input = scanner.nextLine();
            
            // Step 2: Initialize the vowel and consonant counters
            int vowelCount = 0;
            int consonantCount = 0;
            
            // Step 3: Iterate through the string
            for (int i = 0; i < input.length(); i++) {
                char ch = input.charAt(i);
                
                // Check if the character is a vowel
                if (isVowel(ch)) {
                    vowelCount++;
                } 
                // Check if the character is a consonant
                else if (isConsonant(ch)) {
                    consonantCount++;
                }
            }
            
            // Step 4: Display the counts
            System.out.println("Number of vowels: " + vowelCount);
            System.out.println("Number of consonants: " + consonantCount);
        }
    }
    
    // Helper method to check if a character is a vowel
    public static boolean isVowel(char ch) {
        ch = Character.toLowerCase(ch);
        return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
    }
    
    // Helper method to check if a character is a consonant
    public static boolean isConsonant(char ch) {
        ch = Character.toLowerCase(ch);
        return ch >= 'a' && ch <= 'z' && !isVowel(ch);
    }
}
Explanation
Step 1: Read the String
- The Scannerclass is used to read a string input from the user. ThenextLine()method captures the entire line as a string.
Step 2: Initialize Counters
- Two integer variables vowelCountandconsonantCountare initialized to zero. These will hold the counts of vowels and consonants found in the string.
Step 3: Iterate Through the String
- A forloop is used to iterate over each character in the string, using thecharAt()method to access individual characters.
- The isVowel()method checks if a character is a vowel.
- The isConsonant()method checks if a character is a consonant.
Step 4: Display the Counts
- The program prints the total number of vowels and consonants found in the string using System.out.println().
Output Example
Example:
Enter a string: Hello World
Number of vowels: 3
Number of consonants: 7
Conclusion
This Java program demonstrates how to count and display the number of vowels and consonants in a user-input string. It covers essential concepts such as string manipulation, loops, and conditionals, making it a useful exercise for beginners learning Java programming.