brandon russk
brandon russk

Reputation: 41

How do I use the Character Class to check if the user prompted SSN is valid?

I am new to Computer Science and I have an assignment that requires me to create a static boolean method using the Character Class that validates if the user inputted SSN. The acceptable formats are only XXXXXXXXX or XXX-XX-XXXX. I know I am supposed to use Character.isDigit() or charAtString but I have tried them and it doesn't work.

I am sorry if this is a dumb question and I would appreciate your guidance.

Thanks,

Brandon

import java.util.Scanner; // INPUTS SCANNER

public class SSNValidator {
    public static boolean isValidSSN(String ssn) {

}

public static void main(String[]args){

    Scanner input = new Scanner(System.in);
    String programState = "running";

    do {
        System.out.println("Enter a SSN(Quit/quit to exit):\n");
    } while ((!programState.equals("yes")) && (!programState.equals("Yes")));
    System.out.println("Exiting Program.\n");   
}

}

Upvotes: 4

Views: 64

Answers (1)

Rann Lifshitz
Rann Lifshitz

Reputation: 4090

I would suggest you use the following algorithm :

  1. If the string input is the size of 9 - return true after looping on all the characters and confirming (isDigit()) they are digits. (this is the 1st use case for XXXXXXXXX).
  2. Otherwise, if the input string is the size of 11, and the characters at the 3rd and 6th positions are '-' - return true after looping on all the remaining characters and confirming (isDigit()) they are digits. (this is the 2nd use case for XXX-XX-XXXX). When looping you should skip the isDigit() check on the 3rd and 6th positions.
  3. Otherwise, return false (did not match the use cases).

As stated earlier by Davy M - the core of the solution is a recurring loop of isDigit checks. This snippet should be a good reference on how to do this:

String str = "lmn67up94h";
for(char c : str.toCharArray()) {
   if(Character.isDigit(c)) {
      System.out.println("Got digit : " + c);
   }
}

And the output is:

Got digit : 6
Got digit : 7
Got digit : 9
Got digit : 4

Upvotes: 1

Related Questions