Java Code Example: advanced switch-case statement

The code defines a Java class VowelOrConsonant that has two methods: checkCharacter and main.

The checkCharacter method takes a single character input and checks whether it is a vowel or a consonant. It uses a switch statement to check if the input is any of the vowels (a, e, i, o, u, A, E, I, O, or U). If the input is a vowel, the method sets the isVowel variable to true. If the input is not a vowel, it checks if it’s a letter of the alphabet (a-z or A-Z). If it is, it’s a consonant, and the method prints that it’s a consonant. If it’s not a letter of the alphabet, the method prints an error message.

The main method is the entry point of the program. It uses a Scanner object to read a character from the user. It then calls the checkCharacter method, passing the input character as an argument. The checkCharacter method determines whether the character is a vowel or a consonant, and prints the result.

This program can be used to check if a single character entered by the user is a vowel or a consonant.

import java.util.Scanner;

class VowelOrConsonant {
    public static void checkCharacter(char input) {
        boolean isVowel = false;
        switch (input) {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
            case 'A':
            case 'E':
            case 'I':
            case 'O':
            case 'U':
                isVowel = true;
        }
        if (isVowel) {
            System.out.println(input + " is a vowel");
        } else {
            if ((input >= 'a' && input <= 'z') || (input >= 'A' && input <= 'Z'))
                System.out.println(input + " is a consonant");
            else
                System.out.println("error");
        }
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        char input;

        System.out.println("Please enter a character: ");
        input = scan.next().charAt(0);
        scan.close();

        checkCharacter(input);
    }
}
Output 1
Please enter a character: A
A is a vowel
Output 2
Please enter a character: d
d is a consonant