Java program to count the number of consonants in a given sentence


To count the number of consonants in a given sentence:

  •  Read a sentence from the user.
  •  Create a variable (count) initialize it with 0;
  •  Compare each character in the sentence with the characters {'a', 'e', 'i', 'o', 'u' } If match doesn't occurs increment the count.
  •  Finally print count.

Example

import java.util.Scanner;
public class CountingConsonants {
   public static void main(String args[]){
      int count = 0;
      System.out.println("Enter a sentence :");
      Scanner sc = new Scanner(System.in);
      String sentence = sc.nextLine();

      for (int i=0 ; i<sentence.length(); i++){
         char ch = sentence.charAt(i);
         if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ){
            System.out.print("");
         }else if(ch != ' '){
            count++;
         }
      }
      System.out.println("Number of consonants in the given sentence is "+count);
   }
}

Output

Enter a sentence :
Hi hello how are you welcome to tutorialspoint
Number of consonants in the given sentence is 21

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 13-Mar-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements