Question:
Looking for a program to validate a SSN without using loops.
A valid input would be: 123-45-6789
A valid input would be: 123-45-6789
Answer:
See example.
Code:
import java.util.*; public class SSN { public static void main(String args[]){ boolean valid = false; System.out.print("Enter SSN: "); Scanner sc = new Scanner(System.in); String ssn = sc.next(); System.out.println("Input: "+ssn); if(ssn.length()==11) { if( (ssn.charAt(3)=='-') & (ssn.charAt(6)=='-') ) { String str = ssn.replaceAll("-", ""); if (str.matches("[0-9]+") & str.length()==9) { valid = true; } } } System.out.println("valid: " + valid); } }
Output:
$ java SSN Enter SSN: 123-12-1234 Input: 123-12-1234 valid: true $ java SSN Enter SSN: 123-123-123 Input: 123-123-123 valid: false $ java SSN Enter SSN: 123-12-123a Input: 123-12-123a valid: false