A person's social security number is in a specific format:
nnn-nn-nnnn
For example, this is an example of a valid social security number: 111-22-3333. Note that this is just a fictitious example for this article.
An algorithm to verify that a social security number is valid starts with rules:
- The social security number must be a string.
- The string must be of length 11.
- There are hyphen (
-
) characters in the 3rd and 6th positions of the string (starting with position0
). - All other characters in the string must be digits in the range
0
to9
.
Here are some sample social security numbers that fail to meet these requirements:
111223333
- length is not 11 and hyphens are missing11-1223-333
- hyphens are in the wrong positions111-aa-3333
- non-numeric characters are in positions4
and5
111-22-333
- length is not 11
Here is one possible algorithm to verify the format of a social security number:
- Input the social security number as a string value.
- Check the length of the social security number.
- If the length is not equal to 11, output a message that the social security number is invalid and exit the program.
- Otherwise, continue to the next step.
- Check that positions
3
and6
of the social security number are hyphen (-
) characters. One way to do this is with the Java String method charAt() .- If one or both of the positions is not the hyphen (
-
) character, output a message that the social security number is invalid and exit the program. - Otherwise, continue to the next step.
- If one or both of the positions is not the hyphen (
- Check that all other positions in the social security number are numbers in the range
0
-9
. One way to do this is with the Java String method isDigit().- If at least one of these characters is not a digit, output a message that the social security number is invalid and exit the program.
- Otherwise, output a message that the social security number is valid.
This just one possible algorithm for verifying the format of a social security number. There are other ways to do this. But algorithm development is the focus here. Develop a solid algorithm before writing code. Then it is just a matter of translating the algorithm into real Java statements.
Thanks for reading. ๐
Follow me on Twitter @realEdwinTorres
for more programming tips and help.