Count Consonants in a Given Sentence in Java



In this article, we will count the number of consonants in a given sentence using Java to achieve this, we will use the Scanner class for user input and a for loop to iterate through each character in the sentence. By comparing each character with the vowels a, e, i, o, u, and ignoring spaces, we will identify consonants and increment a counter accordingly. The Scanner class is part of java.util package and is commonly used to obtain input from the user.

Problem Statement

Given a sentence, write a Java program to count the number of consonants. As given below ?

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

Steps to count the number of consonants in a given sentence

Following are the steps to count the number of consonants in a given sentence in Java ?

  • Import the Scanner class from java.util package.
  • Read a sentence from the user.
  • Create a variable (count) and initialize it with 0.
  • Compare each character in the sentence with the characters a, e, i, o, and u.
  • If a match doesn't occur increment the count.
  • Finally print count.

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

Below is an example of counting the number of consonants in a given sentence in Java ?

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

Code Explanation

The above program begins by importing the Scanner class and initializing the count variable to 0. The user is prompted to enter a sentence, which is read using Scanner.nextLine(). A for loop iterates through each character of the sentence. Inside the loop, we use charAt() to get each character and compare it with the vowels a, e, i, o, and u. If the character is not a vowel and not a space, we increment the count. Finally, the total number of consonants is printed.

Updated on: 2024-08-08T17:37:15+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements