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;
}
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;
}
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.