Add a method named getSSN to the Validator class that accepts and validates a so
ID: 3531477 • Letter: A
Question
Add a method named getSSN to the Validator class that accepts and validates a social security number. This method should accept a Scanner object and a string that will be displayed to the user as a prompt. After it accepts the social security number, this method should validate the entry by checking that the number consists of three numeric digits, followed by a hyphen and two numeric digits, followed by a hyphen and four numeric digits. If the user's entry doesn't conform to this format, the method should display an error message and ask the user to enter the number again.
Explanation / Answer
import java.util.Scanner;
public class SSN
{
public static void main(String[] args)
{
Scanner kbinput = new Scanner(System.in);
System.out.print("Enter a string for SSN in format XXX-XX-XXXX: ");
String s = kbinput.nextLine();
if (isValidSSN(s)) {
System.out.println("Valid SSN");
}
else
System.out.println("Invalid SSN");
}
public static boolean isValidSSN(String ssn)
{
return (ssn.length() == 11) &&
(Character.isDigit(ssn.charAt(0))) &&
(Character.isDigit(ssn.charAt(1))) &&
(Character.isDigit(ssn.charAt(2))) &&
(ssn.charAt(3) == '-') &&
(Character.isDigit(ssn.charAt(4))) &&
(Character.isDigit(ssn.charAt(5))) &&
(ssn.charAt(6) == '-') &&
(Character.isDigit(ssn.charAt(7))) &&
(Character.isDigit(ssn.charAt(8))) &&
(Character.isDigit(ssn.charAt(9))) &&
(Character.isDigit(ssn.charAt(10)));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.