charAt - number validation in a string

66 Views Asked by At

I have a problem where I need to ensure that the last two digits in a string (called id) are between the numbers of 01 and 40. I thought I had figured it out, however my testing fails when '00' is used - this should fail but it passes.

I know why it is doing this (due to the greater than/less than) but I can't seem to work out how to overcome this problem. Do I need to join characters 10 and 11 together a string then attache further conditional formatting this way?

{
if ((id.charAt(10)<='0'&& id.charAt(11)<= '9')
return true;
}
else {
return false;
}
}
1

There are 1 best solutions below

0
Philippe Fery On

You can use the method described by 'JustAnotherDeveloper' in the comments (see method isBetween2 below) but it means you rely on Integer.parseInt(String) and on the NumberFormatException that may be thrown to define if the 2 characters at index 10 & 11 are numeric or not, which is not really the best solution.

Yous should use regular expressions instead to ensure the two characters are digits (see method isBetween below).

Please not that in the example below, the regular expression pattern will accept any alphanumeric characters for the 10 first characters. You will have to modify the pattern if needed.

public boolean isBetween(String id) {
    Pattern p = Pattern.compile("([[a-zA-Z0-9]]{10})([0-9]{2})");
    Matcher n = p.matcher(id);
    if (n.find()) {
        int i = Integer.parseInt(n.group(2));
        return i >= 1 && i <= 40;
    } else {
        return false;
    }
}

public boolean isBetween2(String id) {
    String s = id.substring(10, 12);
    int i;
    try {
        i = Integer.parseInt(s);
        return i >= 1 && i <= 40;
    } catch (NumberFormatException e) {
        return false;
    }
}