Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

return true if the input [the input character] is ‘a’-‘z’ or ‘A’-‘Z’, return false otherwise

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) {

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading