Count Vowels in Java
Count the number of vowels in a string.
BeginnerModule 4: String ProgramsExample 3 of 25
count-vowels.java
1import java.util.Scanner;23public class Main {4 private static boolean isVowel(char c) {5 c = Character.toLowerCase(c);6 return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';7 }89 public static void main(String[] args) {10 Scanner sc = new Scanner(System.in);11 System.out.print("Enter a string: ");12 String s = sc.nextLine();1314 int count = 0;15 for (int i = 0; i < s.length(); i++) {16 if (isVowel(s.charAt(i))) {17 count++;18 }19 }20 System.out.println("Vowels: " + count);21 sc.close();22 }23}
Output
Enter a string: hello world Vowels: 3
What's going on
We scan each character and increment count when it is a vowel.