Site icon

Program to count & print vowels, consonant in String (java /example)

Examples: Vowels & Consonants in English

Example : 
Input String = "Hello Java"
Number of vowels in given string are 4
Number of consonants are 6

Algorithm: count vowels & consonants of String in Java:

  1. User enter the input string.
  2. Convert input string to lowercase
  3. Iterate through input string:
    1. Check given character is vowel
      1. If character is vowel then increment vowel count.
    2. Check given character is consonant if chInput >= ‘a’ && chInput <= ‘z’
      1. If character is consonant then increment consonant count.
  4. Print number of vowels & consonants.

Program: count number of vowels & consonants in Java

package org.learn.beginner;

import java.util.Scanner;

public class CountVowelAndConsonant {

    public static void main(String[] args) {

        String VOWEL = "aeiou";
        int iVowels = 0, iConsonants = 0;

        try(Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter input string : ");
            String input = scanner.nextLine().toLowerCase();

            for(char chInput : input.toCharArray()) {
                String strChar = String.valueOf(chInput);
                if(VOWEL.contains(strChar)) {
                    iVowels++;
                }
                else if(chInput >= 'a' && chInput <= 'z') {
                    iConsonants++;
                }
            }

            System.out.printf("Vowel Count: %d \n", iVowels);
            System.out.printf("Consonant Count: %d ",iConsonants);
        }
    }
}

Output: print number of vowel & consonant of string in java

Enter input string : Hello Java
Vowel Count: 4 
Consonant Count: 5 
Exit mobile version