Results 1 to 3 of 3

Thread: loop that checks for digits and hiphens

  1. #1
    New Member
    Join Date
    Sep 06
    Posts
    1

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

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 05
    Location
    Happily misplaced
    Posts
    2,513

    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

  3. #3
    PowerPoster
    Join Date
    Nov 02
    Location
    Manila
    Posts
    7,624

    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
  •