Java Program to count total vowels in a String.
Objective
Write a Java program to count the total number of vowels in a given string.
Algorithm / Approach
- Prompt the user to enter a string and store it.
- Initialize a
countvariable to 0. - Start a
forloop from 0 tolength() - 1. - Extract the character at the current index using
charAt(i). - Use an
ifcondition to check if the character matches any vowel (A, E, I, O, U, a, e, i, o, u). - If it matches, increment the
count. - Print the final count.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter String: ");
String s1 = s.nextLine();
char x;
int count=0;
for(int i=0; i< s1.length(); i++)
{
x = s1.charAt(i);
if(x=='A' ||x=='E'||x=='I'||x=='O'
||x=='U'||x=='a'||x=='e'||x=='i'
||x=='o'||x=='u') {
count++;
}
}
System.out.print("Vowels = "+count);
}
}
Expected Output
Enter String: Java Prowess Vowels = 4
Explanation of the Program
- The
charAt()method is crucial here. It allows us to process the string character by character, much like navigating an array. - The
ifstatement uses the logical OR (||) operator to check against all 10 possible vowel characters (5 uppercase + 5 lowercase). - Alternatively, you could convert the entire string to lowercase first using
toLowerCase()to halve the number of comparisons needed in theifstatement.
Complexity
Time Complexity
O(n) - Where n is the length of the string.
Space Complexity
O(1)
Common Mistakes
- Using double quotes (
"A") instead of single quotes ('A') in the if condition.charAt()returns a primitivechar, which must be compared using single quotes.