Home » Java programs

Java program to count number of vowels in a string



In this article of java program, we will learn how to count the number of vowels in a string?
Submitted by Jyoti Singh, on October 05, 2017

Given a string and we have to count total number of vowels in it using Java.

Example:

Input string: "includehelp"
Output:
Number of vowels: 4

In this code we have one input:

  1. An int input (no. of test cases or more clearly the number of strings user wants to check (say 5 i.e user wants to check 5 strings and the program will continue for 5 inputs).
  2. A string input (It will be a string entered by the user which needs to be checked).

For each string we will have two outputs

The number of vowels in string

Consider the program: It will take number of inputs, string and print total number of vowels.


import java.util.Scanner;

public class CountVowels {

	public static void main(String[] args) {
	
		Scanner Kb=new Scanner(System.in);
		System.out.println("How man strings u want to check?");
		//Take the input of no. of test cases
		int t=Kb.nextInt();
		//looping until the test cases are zero
		while(t-->0){
			//Input the string
			System.out.println("Enter the string!");
			String s=Kb.next();
			//counter to count the number of vowels in a string
			int vowels=0;
			for(int i=0;i<s.length();i++){
				//character at a particular index of string
				char ch=s.charAt(i);
				/*switch is used to check multiple condition by using different cases
				here,we will check each character that it is a vowel or not 
				*/
				switch(ch){
					case 'a':
					case 'e':
					case 'i':
					case 'o':
					case 'u':
					case 'A':
					case 'E':
					case 'I':
					case 'O':
					case 'U':
					//counter vowels will be incremented each time when a character will be a vowel
					vowels++;
					break;
					default:
					// do nothing
				}
			}
			//print the number of vowels in a string
			System.out.println(vowels);
		}
		//to give a space of one line
		System.out.println();

	}
}





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.