Program to accept a string from the console and count number of vowels, consonants, digits, tabs and blank spaces in a string
In this program, we have to get a string from user and display the number of vowels, consonants, digits, tabs and blank spaces in that string. To accomplish this we first read a string from keyboard. After that we take a single character at a time upto the last character in given string and compare it for vowel, consonant, digit, tab and blank spaces. For examlple, let us consider the string "abc". In this string we first read the character 'a', then we read character 'b' and finally we read character 'c' Then we will get output as below:
Number of vowels: 1
Number of consonants: 2
The logic for this is given in the program.
PROGRAM
Number of vowels: 1
Number of consonants: 2
The logic for this is given in the program.
PROGRAM
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Vowels {
public static void main(String args[]) throws IOException {
String str;
int vowels = 0, consonants = 0, digits = 0, tabs = 0, blanks_spaces = 0, other = 0;
char ch;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a String : ");
str = br.readLine();
for(int i = 0; i < str.length(); i ++) {
ch = str.charAt(i);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' ||
ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
{
vowels ++;
}
else if(ch == '0' || ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5' ||
ch == '6' || ch == '7' || ch == '8' || ch == '9')
{ // You can use "Character.isDigit(ch)" condition
digits ++;
}
else if(ch == '\t') // Or you can use "Character.isWhitespace(ch)"
{
tabs ++;
}
else if(ch == ' ')
{
blanks_spaces++;
}
else if(Character.isAlphabetic(ch))
{
consonants++;
}
else
{
other++;
}
}
System.out.println("No. of Vowels : " + vowels);
System.out.println("No. of consonants : " + consonants);
System.out.println("No. of Digits : " + digits);
System.out.println("No. of Tabs : " + tabs);
System.out.println("No. of Blank Spaces : " + blanks_spaces);
System.out.println("No. of other characters : " + other);
}
}
OUTPUT
C:\>javac Vowels.java C:\>java Vowels Enter a String : This program is easy 2 understand ! No. of Vowels : 9 No. of consonants : 18 No. of Digits : 1 No. of Tabs : 1 No. of Blank Spaces : 6 No. of other characters : 1