A person's social security number is in a specific format with numbers and dashes:
nnn-nn-nnnn
For example, this is an example of a valid social security number:
111-22-3333
Note that this number is fictitious for this article.
To verify that a social security number is valid, follow these rules:
- The social security number must be a string.
- The string must be of length 11.
- Starting with position
0, there are hyphen (-) characters in the 3rd and 6th positions. - All other characters in the string must be digits in the range
0to9.
Here are some sample social security numbers that fail to meet these requirements:
-
111223333- length is not 11 and hyphens are missing -
11-1223-333- hyphens are in the wrong positions -
111-aa-3333- non-numeric characters are in positions4and5 -
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
3and6of the social security number are hyphen (-) characters. One way to do this is with the Java String charAt() method.- 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 string 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.
Top comments (0)