Java Online Compiler
Example: Count Vowels and Consonants - Basic Iteration in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Count Vowels and Consonants - Basic Iteration import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize Scanner and get input string Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String inputString = scanner.nextLine(); scanner.close(); // Step 2: Initialize counters int vowelCount = 0; int consonantCount = 0; // Step 3: Iterate through each character of the string for (int i = 0; i < inputString.length(); i++) { char ch = inputString.charAt(i); // Step 4: Convert character to lowercase for case-insensitive comparison char lowerCh = Character.toLowerCase(ch); // Step 5: Check if the character is an alphabet if (Character.isLetter(lowerCh)) { // Step 6: Check if it's a vowel if (lowerCh == 'a' || lowerCh == 'e' || lowerCh == 'i' || lowerCh == 'o' || lowerCh == 'u') { vowelCount++; } else { // Step 7: If not a vowel but an alphabet, it's a consonant consonantCount++; } } } // Step 8: Print the results System.out.println("Vowels: " + vowelCount); System.out.println("Consonants: " + consonantCount); } }
Output
Clear
ADVERTISEMENTS