Here’s a Java program to count the number of vowels and consonants in a string:
import java.util.Scanner;
public class VowelConsonant {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
int vowelCount = 0, consonantCount = 0;
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
} else {
consonantCount++;
}
}
}
System.out.println("Number of vowels: " + vowelCount);
System.out.println("Number of consonants: " + consonantCount);
}
}
In this program, we first take user input for a string. We then count the number of vowels and consonants in the string.
We first initialize two integer variables `vowelCount` and `consonantCount` to 0. We convert the string to lowercase using the `toLowerCase()` method to simplify our vowel checking logic. We use a for loop to iterate over each character in the string. For each character, we check if it is a letter using the ASCII values of the letters. If it is a letter, we check if it is a vowel using an if-else statement. If it is a vowel, we increment `vowelCount`. Otherwise, we increment `consonantCount`.
At the end of the program, we print out the number of vowels and consonants in the string.