Write a Java method to count all vowels in a string
This Java program prompts the user to enter a string and then counts the number of vowels in the string. Here's a step-by-step explanation of how the program works:
- The program begins by importing the Scanner class, which is used to read user input from the command line.
- The main method is defined, which is the entry point of the program.
- A new Scanner object is created and assigned to the variable input.
- The program prompts the user to enter a string by calling System.out.print() method with the message "Enter the String: ".
- The user enters a string, which is read by calling the nextLine() method on the Scanner object input, and is assigned to the variable str.
- An integer variable count is declared and initialized to zero. This variable will be used to keep track of the number of vowels in the string.
- A for loop is used to iterate over each character in the string, starting from the first character (which has index 0) and ending with the last character (which has index str.length() - 1).
- For each character in the string, the program checks if it is a vowel by using a series of if statements. If the character is a vowel (either lowercase or uppercase), the count variable is incremented.
- After the for loop finishes iterating over all the characters in the string, the program prints the number of vowels found in the string by calling System.out.print() method with the message "Number of Vowels in the string: " concatenated with the value of the count variable.
Overall, this program is a simple example of how to count the number of vowels in a string using a for loop and conditional statements in Java.
Source Code
import java.util.Scanner;
public class Count_Vowel
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the String : ");
String str = input.nextLine();
int count = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'|| str.charAt(i) == 'o' || str.charAt(i) == 'u' || str.charAt(i) == 'A' || str.charAt(i) == 'E' || str.charAt(i) == 'I' || str.charAt(i) == 'O' || str.charAt(i) == 'U')
{
count++;
}
}
System.out.print("Number of Vowels in the string: " + count);
}
}
Output
Enter the String : Tutor Joes
Number of Vowels in the string: 4