Wednesday 27 July 2016

Chapter 4 Exercise 21, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*4.21 (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. Here are sample runs:

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

Enter a SSN: 23-23-5435
23-23-5435 is an invalid social security number


import java.util.Scanner;
 
public class ProgrammingEx4_21 {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter a SSN:");
  String s = input.nextLine();
 
  for (int i = 0; i < s.length(); i++) {
   if ((i == 3 || i == 6) && s.charAt(i) == '-') {
    continue;
   }
   if (!Character.isDigit(s.charAt(i))) {
    System.out.println(s + " is an invalid social security number");
    System.exit(0);
   }
  }
 
  System.out.println(s + " is a valid social security number");
 }
 
}

No comments :

Post a Comment