Write a Java program to input a sentence and count the number of words that start with a vowel (A, E, I, O, U). The program should be case-insensitive and display the count.
Example:
Input: "An elephant is outside the umbrella"
Output: Number of words starting with a vowel: 4
import java.util.Scanner;
public class VowelWordCounter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input sentence
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();
sc.close();
int vowelWordCount = 0;
int length = sentence.length();
boolean isWord = false; // Flag to track a new word
for (int i = 0; i < length; i++) {
char ch = sentence.charAt(i);
// Check if current character is a letter (indicating start of a word)
if (Character.isLetter(ch)) {
if (!isWord) { // New word detected
isWord = true;
char firstChar = Character.toLowerCase(ch); // Convert to lowercase
if ("aeiou".indexOf(firstChar) != -1) { // Check if it starts with a vowel
vowelWordCount++;
}
}
} else {
isWord = false; // Reset flag when encountering space or punctuation
}
}
// Output the count
System.out.println("Number of words starting with a vowel: " + vowelWordCount);
}
}
✅ Loops through each character in the sentence.
✅ Detects the start of a word (first letter after a space or punctuation).
✅ Checks if the first letter is a vowel (aeiou).
✅ Counts only words that start with vowels.
Output:
Enter a sentence: An elephant is outside the umbrella
Number of words starting with a vowel: 4



