InterviewSolution
Saved Bookmarks
| 1. |
Write a program in Java to count the total number of vowels and consonants in a String. The string can contain all the alphanumeric and other special characters as well. However, only the lowercase English alphabets are allowed in the String. |
|
Answer» We just have to traverse the string. If we get any vowel (a,e,i,o,u), we increment the variable corresponding to the vowel count and if we get a consonant, we increment the variable corresponding to the consonant count. Java Code to Count Vowels and Consonants in a String import java.util.*;class Main { public static boolean isVowel(char ch) { if(ch == 'a' || ch =='e' || ch =='i' || ch =='o' || ch =='u') return true; return false; } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); String str = scn.nextLine(); int vowelCount = 0; int consCount = 0; for(int i=0;i<str.length();i++) { char ch = str.charAt(i); if(isVowel(ch) == true) vowelCount++; else if(ch >='a' && ch<='z' && isVowel(ch) == false) consCount++; } System.out.println("Number of vowels are: " + vowelCount); System.out.println("Number of consonants are: " + consCount); System.out.println("Number of other characters are: " + (int)(str.length() - vowelCount -consCount)); } } Sample Output Input: ae#zyu*Output: The number of vowels is: 3 The number of consonants is: 2 The number of other characters is: 2
|
|