Java program to accept a string and count number of Vowels present in it

Java program to accept a string and count number of Vowels present in it

1. Using enhanced for loop (for-each)
2.Change the string to either lower or upper case so that we don't have to check the condition for 'A' and the again for 'a'.


import java.util.Scanner;

public class demo{

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a String: ");

String str = sc.nextLine();

sc.close();

int count = demo.capitalCount(str);

System.out.print(count);

}

static int capitalCount(String str) {

int totalCount = 0;

for(char c : str.toLowerCase().toCharArray()) {

    if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )

        ++totalCount;

}

return totalCount;

}

}



[NOTE: there are many different ways this problem can be solved]

Comments