Count The Words Starting With Vowels in Java

Published by user on

In this post, we will look at how to count the words starting with vowels in Java.

We will accept the String and then check if any words start with ‘A’, ‘E’, ‘I’, ‘O’, and ‘U’ or lower case ‘a’, ‘e’, ‘i’, ‘o’, ‘u’.

First, we will separate the words using the split() method and then check the first character of each word.

Program

Let’s have a look at the program.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// Java program to demonstrate
// how to count the the words
// starting with vowels
public class VowelCounter {
        public static void main(String[] args) throws IOException {
                // BufferedReader to accept the string
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

                System.out.print("Enter Sentence: ");

                // read the string from
                // command line
                String str = br.readLine();

                String[] words = str.split(" ");

                int counter = 0;

                for (int i = 0; i < words.length; i++) {
                        char firstChar = words[i].charAt(0);

                        // check if first character
                        // of word starts with either
                        // upper or lower case vowels
                        if (firstChar == 'A' || firstChar == 'E' || firstChar == 'I' 
                                        || firstChar == 'O' || firstChar == 'U'
                                        || firstChar == 'a' || firstChar == 'e' || firstChar == 'i' 
                                        || firstChar == 'o' || firstChar == 'u') {
                                // increase the counter
                                counter++;
                                System.out.println(words[i]);

                        }
                }
                System.out.println("Number of Words Starting with vowel = " + counter);
        }
}

Output:

Enter Sentence: I own an Apple Laptop, it runs fast
I
own
an
Apple
it
Number of Words Starting with vowel = 5
Categories: Java