|
-
Dec 9th, 2007, 07:07 PM
#1
Thread Starter
New Member
loop that checks for digits and hiphens
I have to write a loop that steps through each character of a string checking for a digit and a hyphen in a social security number. how can i write the loop if I have an if statement already made for the other items i have to check for already such as the following code I have. Thanks
if (ssn.length() != 11)
{
throw new SocSecException(" wrong number of characters.");
}
else if (ssn.charAt(3) != '-' || ssn.charAt(6) != '-')
{
throw new SocSecException(" dashes at wrong positions.");
}
else
{
return true;
}
-
Dec 10th, 2007, 06:14 AM
#2
Re: loop that checks for digits and hiphens
Take a look at this code. Hope it helps:
Code:
public static boolean validSSN(String ssn) {
for (int i = 0; i < ssn.length(); i++) {
if (!Character.isDigit(ssn.charAt(i)) || (ssn.charAt(i) == '-' && (i == 3 || i == 6)))
return false;
}
return ssn.length() == 11;
}
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Dec 17th, 2007, 05:45 AM
#3
Re: loop that checks for digits and hiphens
Split the string then check accordingly, eg. check array ubound which tells if correct number of groups (dashes) exist, check each array element for length and/or datatype (expected number in so and so range), etc etc.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|