🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
Counting the number of vowels and consonants in a string is a common task in text processing and analysis. This guide will show you how to create a Java program that counts and displays the number of vowels and consonants in a given string.
Problem Statement
Create a Java program that:
- Takes a string as input.
- Counts and displays the number of vowels and consonants in the string.
Example 1:
- Input:
"Hello World" - Output:
Vowels: 3, Consonants: 7
Example 2:
- Input:
"Java Programming" - Output:
Vowels: 5, Consonants: 9
Solution Steps
- Prompt for Input: Use the
Scannerclass to read a string input from the user. - Initialize Counters: Initialize variables to count the number of vowels and consonants.
- Iterate Through the String: Loop through each character in the string, checking if it's a vowel or consonant.
- Display the Counts: Print the number of vowels and consonants.
Java Program
Java Program to Count Vowels and Consonants in a String
import java.util.Scanner;
/**
* Java Program to Count Vowels and Consonants in a String
* Author: https://www.javaguides.net/
*/
public class VowelConsonantCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Prompt the user for input
System.out.print("Enter a string: ");
String input = scanner.nextLine();
// Step 2: Initialize counters
int vowels = 0, consonants = 0;
input = input.toLowerCase(); // Convert the string to lowercase
// Step 3: Iterate through the string and count vowels and consonants
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (ch >= 'a' && ch <= 'z') { // Check if the character is a letter
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}
// Step 4: Display the counts
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}
Explanation
- Input: The program prompts the user to enter a string.
- Counting Vowels and Consonants: The string is first converted to lowercase to handle case insensitivity. The program then iterates through each character in the string:
- If the character is a vowel (a, e, i, o, u), the
vowelscounter is incremented. - If the character is a letter but not a vowel, the
consonantscounter is incremented.
- If the character is a vowel (a, e, i, o, u), the
- Output: The program prints the number of vowels and consonants in the input string.
Output Example
Example 1:
Enter a string: Hello World
Vowels: 3
Consonants: 7
Example 2:
Enter a string: Java Programming
Vowels: 5
Consonants: 9
Example 3:
Enter a string: Vowel Consonant Counter
Vowels: 7
Consonants: 13
Alternative Approach: Using Java 8 Streams
import java.util.Scanner;
import java.util.stream.Stream;
/**
* Java Program to Count Vowels and Consonants in a String using Java 8 Streams
* Author: https://www.javaguides.net/
*/
public class VowelConsonantCounterStreams {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Prompt the user for input
System.out.print("Enter a string: ");
String input = scanner.nextLine().toLowerCase(); // Convert to lowercase
// Step 2: Count vowels using streams
long vowelCount = input.chars()
.filter(c -> "aeiou".indexOf(c) != -1)
.count();
// Step 3: Count consonants using streams
long consonantCount = input.chars()
.filter(c -> c >= 'a' && c <= 'z' && "aeiou".indexOf(c) == -1)
.count();
// Step 4: Display the counts
System.out.println("Vowels: " + vowelCount);
System.out.println("Consonants: " + consonantCount);
}
}
Explanation
- Counting Vowels and Consonants Using Streams: This approach leverages Java 8's
StreamAPI to filter and count vowels and consonants. Thechars()method converts the string into anIntStreamof character codes. Thefilter()method is used to check whether each character is a vowel or consonant, and thecount()method returns the count.
Output Example
Enter a string: Java 8 Streams
Vowels: 4
Consonants: 6
Conclusion
This Java program provides two methods for counting the number of vowels and consonants in a string: a traditional loop and Java 8 streams. Both methods are effective, with the loop method being more straightforward and the stream method offering a more modern and functional approach. These methods are useful in various text-processing tasks, such as analyzing content or validating input data.
Comments
Post a Comment
Leave Comment