Input a string and count vowels using a function in Java
Function - Question 2
In this question, we will see how to input a string and count how many vowels are there in it in Java programming using a function. To know more about function click on the function lesson.
Q2) Write a program in Java to input a string and count how many vowels are there in it using a function.
Program
import java.util.Scanner;
public class Example
{
public static int countvowels(String str)
{
int vc=0,i;
char ch;
for(i=0; i<str.length(); i++)
{
ch=Character.toLowerCase(str.charAt(i));
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
{
vc=vc+1;
}
}
return vc;
}
public static void main(String args[])
{
String s;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number ");
s=sc.nextLine();
System.out.print("Total Number of Vowels = " + countvowels(s));
}
}
Output
Enter a String: I am learning Java Total Number of Vowels = 7