I've been doing exercise. Write a Java program that takes the user to provide a single character from the alphabet. Print Vowel of Consonant, depending on the 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. And that's an answer:
import java.util.Scanner;
public class Exercise8 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input a 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
{`enter code here`
System.out.println("Input letter is Consonant");
}
}
}
How comes that,
boolean uppercase = input.charAt(0) >= 65 && input.charAt(0) <= 90;
works? Shouldn't input.charAt()
return a String?
Also, why is there distinction for uppercase and lowercase in the second half of a code if someone used
toLowerCase();
already?
It seems like you have both the Question and the Answer. And you need to know how charAt(0) works in first place, secondly you want to know how the code actually works.. If you are wondering why your question is being downvoted,then this is the answer.
SE is not a code review site. If you have any specific doubts with regard to the working/workflow of the code, then definitely this is your place. Even I experienced the similar situation when I started using SE for the first time. Dont worry about the downvotes, You will become a pro in asking questions through experience.
Now Answering your question:
The java string charAt() method returns a char value at the given index number. The index number starts from 0.
Example:
public class Solution{
public static void main(String args[]){
String name="StackExchange";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}
The output is k ..
Also, why is there distinction for uppercase and lowercase in the second half of a code if someone used
toLowerCase();
This is exactly the way you should refrain from using in SE..
It explicitly tells us this is not your code, and you want people here to teach you the logic of the code.
Anyways answer to this question of yours is,
Yes, it is completely unnecessary to use Uppercase, since you have converted every letter to lowercase, at the input stage itself
Few Insights:
Now that you have understood the logic of this code, try implementing the same with Regular Expressions.
All the best.