Question: Write a program that prompts the user to enter a letter and check whether the letter is a vowel or consonant. Must display any input with non-letter characters. This is based on a question from Java textbook by Dr. Daniel Liang.
Warning!
Please import selected Java packages or use import java.util.*;. Do not copy my code as per copyright and plagiarism regulations. This Java code is provided as it is for demonstration purposes.Solution 1: The following code checks if the user input only contains one letter and display a message when there are more than one letter.
public class VolConst {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a letter: ");
String s = input.nextLine();
if (s.length() != 1) {
System.out.println("You must enter exactly one character");
return;
}
char ch = Character.toUpperCase(s.charAt(0));
if (ch > 'Z' || ch < 'A') {
System.out.println(s + " is an invalid input");
return;
}
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
System.out.println(s + " is a vowel");
return;
}
System.out.println(s + " is a consonant");
}
}
Solution 2: The following code accomplish the same task but does not verify if the user only input one letter. When a user enter more than one letter, the program takes the first letter in memory.
public class VolConst {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a letter: ");
char letter = input.nextLine().charAt(0);
if (Character.toUpperCase(letter) == 'A' || Character.toUpperCase(letter) == 'E' || Character.toUpperCase(letter) == 'I'
|| Character.toUpperCase(letter) == 'O' || Character.toUpperCase(letter) == 'U')
System.out.println(letter + " is a vowel");
else if (Character.isLetter(letter))
System.out.println(letter + " is a consonant");
else
System.out.println(letter + " is an invalid input");
}
}
Note the Character.isLetter() function can be used to check if the user entered anything other than letters.
Output:
Sample Run 1
Enter a letter: B
B is a consonant
Sample Run 2
Enter a letter grade: a
a is a vowel
Sample Run 3
Enter a letter grade: #
# is an invalid input