In this tutorial you will learn about the Java Program to Count the Number of Vowels and Consonants in a Sentence and its application with practical example.
In this tutorial, we will learn to create a Java Program that Count the Number of Vowels and Consonants in a Sentence using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output
- Class and Object.
- Basic Java programming.
- if-else statements.
- Java Scanner class.
What Is Vowel and consonant?
Vowel :=> Sound that allowing breath to flow out of mouth, without closing any part of the mouth is called as vowel.
Consonant:=> Sound made by blocking air from flowing out of the mouth with the teeth or throat is called as Consonant.
Example:- As we know that “A E I O U” are vowels. And renaming alphabets except these 5 vowels are called consonants.
Java Program to Count the Number of Vowels and Consonants in a Sentence
In this our program we will create a Program to Count the Number of Vowels and Consonants in a Sentence . We would first declared and initialized the required variables. Next, we would prompt user to input string . Later in program we will find Number of Vowels and Consonants in a Sentence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Cont_vow_cons { public static void main(String[] args) { String strng = "awesomw website https://www.w3adda.com/."; int vowel = 0, conso = 0,i; // Declaring variables strng = strng.toLowerCase(); for (i = 0; i < strng.length(); ++i) { char ch = strng.charAt(i); // checking character is any of a, e, i, o, u in string if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++vowel; } // check if character is in between a to z else if ((ch >= 'a' && ch <= 'z')) { ++conso; } } System.out.println("Vowels: " + vowel); System.out.println("Consonants: " + conso); } } |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- strng= it will hold string .
- i= for itreation.
- vowel= it will hold vowels counting.
- conso= it will hold consonants counting.
And in the next statement we will convert into lower case and break the string into character.
Then with the help of if-else statement we will check the string character is a vowel or consonant, using following logic.
Each character in a string is going to be check whether it’s a vowel or Consonant we check it belongs to in vowel or consonant. if it vowel we will increment value of vowel and if it not we will increment value of consonant.
At the end in a program we will show the number or vowel and Consonants present in a string are.
As shown in image above.