Write a method, that returns true or false depending on whether a character (char) [the input] is a valid character to be encoded. I.e. return true if the input [the input character] is ‘a’-‘z’ or ‘A’-‘Z’, return false otherwise.
Why is my answer wrong????
public static boolean isValidChar_Q1(char chr) {
if(chr == 'a'-'z')
{
return true;
}
if(chr == 'A'-'Z')
{
return true;
}
return false;
}
>Solution :
In your comparisons you’re trying to compare a single char to a range, which is something you cannot write like that in Java. That syntax of yours looks closer to a regex ([a-zA-Z]) than a proper Java comparison.
If you want to check whether a variable’s value is within a range, you need to compare it with its boundaries: greater than or equal to the left edge and lower than or equal to the right edge.
public static boolean isValidChar_Q1(char chr) {
return (chr >= 'a' && chr <= 'z') || (chr >= 'A' && chr <= 'Z');
}