w3resource

Java: Find Vowel or Consonant


Check Vowel or Consonant

Write a Java program that requires the user to enter a single character from the alphabet. Print Vowel or Consonant, depending on user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an error message.

Test Data
Input an alphabet: p

Pictorial Presentation:

Java conditional statement Exercises: Find Vowel or Consonant


Sample Solution:

Java Code:

import java.util.Scanner;
public class Exercise8 {

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

        System.out.print("Input an alphabet: ");
        String input = in.next().toLowerCase();

        boolean uppercase = input.charAt(0) >= 65 && input.charAt(0) <= 90;
        boolean lowercase = input.charAt(0) >= 97 && input.charAt(0) <= 122;
        boolean vowels = input.equals("a") || input.equals("e") || input.equals("i")
                || input.equals("o") || input.equals("u");

        if (input.length() > 1)
        {
            System.out.println("Error. Not a single character.");
        }
        else if (!(uppercase || lowercase))
        {
            System.out.println("Error. Not a letter. Enter uppercase or lowercase letter.");
        }
        else if (vowels)
        {
            System.out.println("Input letter is Vowel");
        }
        else
        {
            System.out.println("Input letter is Consonant");
        }
    }
}

Sample Output:

Input an alphabet: P                                                                                          
Input letter is Consonant 

Flowchart:

Flowchart: Java Conditional Statement Exercises - Find Vowel or Consonant



For more Practice: Solve these Related Problems:

  • Write a Java program to determine whether a given character is a vowel or consonant using ASCII values.
  • Write a Java program to check if a single input character is a vowel by comparing it with both uppercase and lowercase vowels.
  • Write a Java program to validate that the input is a single alphabet character and then classify it as vowel or consonant using a switch-case.
  • Write a Java program to use regular expressions to verify if an input character is a vowel and display an error for invalid input.

Go to:


PREV : Days in a Month.
NEXT : Check Leap Year.


Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.