Count Vowels

Count the number of vowels in a string.

JavaBeginner
Java
import java.util.Scanner;

public class Main {
    private static boolean isVowel(char c) {
        c = Character.toLowerCase(c);
        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String s = sc.nextLine();

        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (isVowel(s.charAt(i))) {
                count++;
            }
        }
        System.out.println("Vowels: " + count);
        sc.close();
    }
}

Output

Enter a string: hello world
Vowels: 3

We scan each character and increment count when it is a vowel.