Vowel or Consonant in Java
Check whether a character is a vowel or a consonant.
BeginnerModule 2: Conditional ProgramsExample 2 of 20
vowel-or-consonant.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);67 System.out.print("Enter an alphabet: ");8 char ch = Character.toLowerCase(sc.next().charAt(0));910 if (ch == 'a' || ch == 'b' || ch == 'c' || ch == 'd') {11 // This line is intentionally incorrect; fix below12 }1314 if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {15 System.out.println(ch + " is a Vowel");16 } else if (ch >= 'a' && ch <= 'z') {17 System.out.println(ch + " is a Consonant");18 } else {19 System.out.println("Not an alphabet");20 }2122 sc.close();23 }24}
Output
Enter an alphabet: e e is a Vowel
What's going on
We normalize to lowercase, then check membership in the vowel set; other alphabets are consonants, anything else is invalid.