Java program to count the number of vowels and consonants in a sentence

Sure, here's a Java program that counts the number of vowels and consonants in a sentence:

refer to‮ditfigi:‬ea.com
import java.util.Scanner;

public class CountVowelsAndConsonants {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String sentence = sc.nextLine();
        
        int vowels = 0;
        int consonants = 0;
        
        for (int i = 0; i < sentence.length(); i++) {
            char ch = sentence.charAt(i);
            
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'
                    || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
                vowels++;
            } else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
                consonants++;
            }
        }
        
        System.out.println("Number of vowels: " + vowels);
        System.out.println("Number of consonants: " + consonants);
    }
}

In this program, we first use a Scanner to obtain a sentence from the user. We then define two integer variables vowels and consonants to represent the number of vowels and consonants in the sentence, respectively.

We then use a for loop to iterate through each character in the sentence. For each character, we check if it is a vowel or a consonant. If it is a vowel, we increment the vowels counter. If it is a consonant, we increment the consonants counter.

Note that we check for both uppercase and lowercase vowels. We also check if the character is a letter (i.e., between 'a' and 'z' or between 'A' and 'Z') before checking if it is a consonant. This allows us to ignore spaces, punctuation, and other non-letter characters in the sentence.

Finally, we print out the number of vowels and consonants in the sentence.