DanG
DanG

Reputation: 9

How to test if a string contains numbers at certain points

I have a string with 6 characters in length. The first character must be a capital letter, and the last 5 characters must be digits.

I need to write code to return true if the characters that follow after the capital letter are digits, and false if they are not.

Here is what I have so far, but when testing the code, I get an error:

public boolean hasValidDigits(String s)
{
    if (Character.isDigit(s.charAt(1-5))) {
        return true;
    } else {
             return false;
    }
}

Upvotes: 0

Views: 547

Answers (2)

Piyush Singh
Piyush Singh

Reputation: 611

Check str.matches("[A-Z][0-9]{5}");

Upvotes: 0

Zeta Reticuli
Zeta Reticuli

Reputation: 329

Next time please put the error description. What you need here is Regex which test the string to the pattern.

i.e.:

return s.matches("[A-Z]{1}[0-9]{5}");

[A-Z]{1}[0-9]{5} means: one capital letter, and 5 digits after.

Upvotes: 4

Related Questions