Skip to content

Instantly share code, notes, and snippets.

@gitaficionado
Created September 30, 2019 03:22
Show Gist options
  • Save gitaficionado/1f230f5cba0ed9e1549b6dd7ddcb8e7e to your computer and use it in GitHub Desktop.
Save gitaficionado/1f230f5cba0ed9e1549b6dd7ddcb8e7e to your computer and use it in GitHub Desktop.
(Check SSN) 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. See page 144 for a sample run.
import java.util.Scanner;
public class CheckSocialSecurityNumber_04_21 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a SSN: ");
// create social security number variable
boolean isValid = ssn.length() == 11 &&
ssn.charAt(0) <= '9' && ssn.charAt(0) >= '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));
// crate if/else statement that communicates to user whether the social security number is valid.
if (isValid)
System.out.println(ssn + " is a valid social security number");
else
System.out.println(ssn + " is an invalid social security number");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment