Count Consonants in Java
Count the number of consonants in a string.
BeginnerModule 4: String ProgramsExample 4 of 25
count-consonants.java
1import java.util.Scanner;23public class Main {4 private static boolean isAlphabet(char c) {5 return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');6 }78 private static boolean isVowel(char c) {9 c = Character.toLowerCase(c);10 return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';11 }1213 public static void main(String[] args) {14 Scanner sc = new Scanner(System.in);15 System.out.print("Enter a string: ");16 String s = sc.nextLine();1718 int count = 0;19 for (int i = 0; i < s.length(); i++) {20 char ch = s.charAt(i);21 if (isAlphabet(ch) && !isVowel(ch)) {22 count++;23 }24 }25 System.out.println("Consonants: " + count);26 sc.close();27 }28}
Output
Enter a string: hello Consonants: 3
What's going on
We count alphabetic characters that are not vowels.