Explanation
This Java program is designed to teach fundamental input/output and conditional logic. It prompts the user to enter a single character. The program then checks if the input is indeed a single alphabet character. If it's not, it displays an error message. If it is a single alphabet character, it determines whether that character is a vowel or a consonant and prints the result.
Here's a step-by-step breakdown of the logic:
- Import Scanner: The program starts by importing the
Scannerclass from thejava.utilpackage. TheScannerclass is essential for reading user input from the console. - Create Scanner Object: Inside the
mainmethod, aScannerobject namedinputis created. This object is linked to the standard input stream (System.in), which typically represents the keyboard. - Prompt User: The program displays a message asking the user to "Enter a single character: ".
- Read User Input: The
input.next()method reads the next token (word or sequence of characters separated by whitespace) entered by the user and stores it as aStringin the variables. - Input Validation:
- The
ifstatement checks for invalid input. s.length() != 1: This condition checks if the length of the entered stringsis not equal to 1. If the user enters more than one character or nothing at all, this part of the condition will be true.!Character.isLetter(s.charAt(0)): This condition checks if the first character of the input stringsis not a letter.s.charAt(0)gets the first character, andCharacter.isLetter()returnstrueif it's an alphabet character. The!negates this, so it'strueif the character is not a letter (e.g., a number, symbol, or space).- The
||(OR) operator means that if either of these conditions is true, the entireifcondition is true, and the error message is printed.
- The
- Error Message: If the input is invalid (not a single character or not a letter), the program prints "Error: Please enter only a single alphabet character".
- Vowel/Consonant Check (if input is valid):
- If the input passes the validation (meaning it's a single alphabet character), the
elseblock is executed. char c = Character.toLowerCase(s.charAt(0));: The first character of the input string (s.charAt(0)) is converted to lowercase usingCharacter.toLowerCase()and stored in acharvariable namedc. This makes the vowel check case-insensitive (so 'A' is treated the same as 'a').- The inner
ifstatement checks if the lowercase charactercis equal to 'a', 'e', 'i', 'o', or 'u'. - Vowel Output: If
cmatches any of these vowels, "Vowel" is printed. - Consonant Output: If
cdoes not match any of the vowels, it must be a consonant (since we've already confirmed it's a letter), so "Consonant" is printed.
- If the input passes the validation (meaning it's a single alphabet character), the
- Close Scanner: Finally,
input.close()is called to release the system resources used by theScannerobject. This is good practice.