Exercise:
Write a Java Program to count the number of vowels and consonants in a sentence.
Click Here to View the Solution!
public class CharcterTypeCount {
public static void main(String[] args) {
String line = "I have coded more than 50 programs till yet.";
int digits = 0, spaces = 0 ,vowels = 0, consonants = 0;
line = line.toLowerCase();
for(int i = 0; i < line.length(); ++i)
{
//Checks if the character is a vowel
char ch = line.charAt(i);
if(ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u') {
++vowels;
}
//Checks if the character is a consonant
else if((ch >= 'a'&& ch <= 'z')) {
++consonants;
}
//Checks if the character is a digit
else if( ch >= '0' && ch <= '9')
{
++digits;
}
//Checks if the character is a space
else if (ch ==' ')
{
++spaces;
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Digits: " + digits);
System.out.println("White spaces: " + spaces);
}
}
Click Here to View the Output!
Vowels: 12 Consonants: 21 Digits: 2 White spaces: 8
Click Here to View the Explanation!
- In this program, there are four conditional statements which check against each of the four possibilities.
- Initially there is an if condition, which determines the possibility of a character being a
vowel
. - Next there is an else-if condition checking to see if the character falls in the category of
consonants
. Note that the sequence of these conditions must follow the same order otherwise a vowel would be passed off as a consonant as well. - Furthermore, considering there are no alphabets and the first two conditions are false, the third if-else condition has a check to see if the character lies between the limitation of 0-9. If so, it is
digit
otherwise the last condition is checked. - Lastly there is an if-else statement which matches the given character to a
space
character to see if it matches or not. - To optimize this overall process, the characters in the ‘line’ variable are converted to lowercase letters using
toLowerCase()
function so that the provision of capital alphabets don’t have to be considered in the conditions. - The built-in
length()
function has been utilized for the total string length andcharAt()
for returning characters based on their indexes.