Java Method definition check social security number format

Question

We would like to write a program that prompts the user to enter a Social Security number in the format DDD-DD-DDDD, where D is a digit.

Your program should check whether the input is valid.

Here are sample runs:

Enter a SSN: 232-23-1234 
232-23-1234 is a valid social security number 

Enter a SSN: 23-23-1234 
23-23-1234 is an invalid social security number 
import java.util.Scanner;


public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Format: DDD-DD-DDDD");
        System.out.print("Enter SSN: ");
        String s = input.nextLine();
        input.close();/*  w ww.  ja  v  a  2 s . c  om*/

        if (isSSNValidFormat(s)) {
            System.out.println(s + " is a valid social security number.");
        } else {
            System.out.println(s + " is a INVALID social security number.");
        }
    }

    public static boolean isSSNValidFormat(String s) {

        //your code here

    }
}




import java.util.Scanner;


public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Format: DDD-DD-DDDD");
        System.out.print("Enter SSN: ");
        String s = input.nextLine();
        input.close();

        if (isSSNValidFormat(s)) {
            System.out.println(s + " is a valid social security number.");
        } else {
            System.out.println(s + " is a INVALID social security number.");
        }
    }

    public static boolean isSSNValidFormat(String s) {

        for (int i = 0; i < s.length(); i++) {

            char ch = s.charAt(i);
            if (i == 3 && ch != '-') return false;
            if (i == 6 && ch != '-') return false;
            if (i != 6 && i != 3 && !Character.isDigit(ch)) return false;
        }
        return true;

    }
}



PreviousNext

Related