ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Count the Number of Vowels in Java String

Updated on October 31, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

Count Number of Vowels Java Program

Counting the number of vowels in a string is another Java Program for beginners. At first this program can just read a word because of the limitation in using the next() predefined method, but if you want to read and check the entire string together with the spaces and commas entered, use the predefined method nextline() instead.

This program use the nextLine() predefined method for better demonstration. You can also change it into next() method if you want to see the difference.

Program Algorithm:

The program that is provided in this hub will prompt the user to enter a string according to his wishes and the program would count the number of vowels regardless of how many spaces entered in the string. The vowels will be check using the charAt() predefined method and will loop it until it reach the maximum number of characters that the string has. Whether the vowels are in upper or lower cases the program will still count it, leaving no vowels behind that are uncounted.

See the output of this program. Try it also on your Java IDE. Happy Programming!

Java Source Code: Count Number of Vowels in a String

import java.util.Scanner;


public class Main {

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);


        String word;
        System.out.print("Enter a String: ");
        word = input.nextLine();
        int count =0;


        for(int i = 0; i < word.length(); i++)
        {
            if(word.charAt(i) == 'a' || word.charAt(i) == 'A')
            {
                count++;
            }
            else if(word.charAt(i) == 'e' || word.charAt(i) == 'E')
            {
                count++;
            }
            else if(word.charAt(i) == 'i' || word.charAt(i) == 'I')
            {
                count++;
            }
            else if(word.charAt(i) == 'o' || word.charAt(i) == 'O')
            {
                count++;
            }
            else if(word.charAt(i) == 'u' || word.charAt(i) == 'U')
            {
                count++;
            }
        }
        System.out.println("Number of vowels: " + count);


        
    }

}

Sample Output:

Is this program useful to you? Rate it below. Any question about the program, you are welcome to ask at the comment section.

Comments

Submit a Comment

No comments yet.