Count vowels in a string using Java
Posted by Samath
Last Updated: January 17, 2024

Write a method called vowelCount that accepts a String as a parameter and produces and returns an array of integers representing the counts of each vowel in the string. The array returned by your method should hold five elements: the first is the count of A’s, the second is the count of E’s, the third Is, the fourth 0’s, and the fifth U’s. Assume that the string contains no uppercase letters. For example, the call vowelCount("i think, therefore i am") should return the array {1, 3, 3, 1, 0}.

Solution:

import java.lang.*;
import java.util.Scanner;
public class VowelCount {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int[] my_arr = new int[5];
        System.out.print("Please enter a string: ");
        String word = scan.nextLine();
        my_arr = vowelCount(word);
        

           System.out.print("a: "+my_arr[0]);
           System.out.print("\ne: "+my_arr[1]);
           System.out.print("\ni: "+my_arr[2]);
           System.out.print("\no: "+my_arr[3]);
           System.out.print("\nu: "+my_arr[4]);

    }
    
    public static int[] vowelCount(String str)
    {
        int[] v_count = new int[5];
        for(int i=0;i<str.length();i++)
        {
            if(str.charAt(i)=='a')
            {
                v_count[0]++;
            }
            else if(str.charAt(i)=='e')
            {
                v_count[1]++;
            }
            else if(str.charAt(i)=='i')
            {
                v_count[2]++;
            }
            else if(str.charAt(i)=='o')
            {
                v_count[3]++;
            }
            else if(str.charAt(i)=='u')
            {
                v_count[4]++;
            }
        }
        return v_count;
    }
    
}

 

Related Content