The problem
Write a program that prompts the user to enter a letter and check whether the letter is a vowel or consonant.
Breaking it down
Once the user has inputted a character, we will convert the String into a Instream by calling value.chars()
. Next using a IntPredicate
that checks if character is a vowel we check if any of the values equal a vowel by using Stream.anyMatch()
. Something to note, you may consider scrubbing the input value as a user could enter any number of chars, vowels or consonant and anyMatch
would return true.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a letter: ");
String value = input.next();
input.close();
boolean isVowel = value.chars().anyMatch(vowel);
if (isVowel) {
System.out.println(value + " is a vowel.");
} else {
System.out.println(value + " is a consonant.");
}
}
static IntPredicate vowel = new IntPredicate() {
@Override
public boolean test(int t) {
return t == 'a' || t == 'e' || t == 'i' || t == 'o' || t == 'u'
|| t == 'A' || t == 'E' || t == 'I' || t == 'O' || t == 'U';
}
};
Output
Enter a letter: a
a is a vowel.