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

Time:05-16

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;

}

CodePudding user response:

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

CodePudding user response:

The syntax if(chr == 'a'-'z') is not correct. 'a' and 'z' are both character literals, but in Java a character is a 16-bit integral type. So 'a'-'z' is a long way to write -25. I would simplify the logic and the test. Something like

public static boolean isValidChar_Q1(char chr) {
    char t = Character.toLowerCase(chr);
    return t >= 'a' && t <= 'z';
}

CodePudding user response:

You wrote 'a'-'z' which will convert into ASCII code subtraction and the result will be -25, and as for your 'A'-'Z' statement, the result will be (well, also) -25.

You should write something like

if( (chr <= 'z' && chr >= 'a') || (chr <= 'Z' && chr >= 'A') )
    return true;
return false;

Always remember, that computers work with ASCII codes, rather than "characters", and the computer will check for the valid code of given characters (which are always positive, -25 is not valid), in our case, the ASCII code of chr SHOULD be smaller-or-equal to z, and so on (see the if-statement above).

If you are familiar with overloading the return statement, you could also simplify your function (make it more readable):

return (chr >= 'a' && chr <= 'z') || (chr >= 'A' && chr <= 'Z')

CodePudding user response:

Solution using Regex:

import java.util.regex. * ;

    boolean isMatch = Pattern.matches("[a-zA-Z]", "S");
  • Related