第四章第二十一题(检查 SSN)(Check SSN)
-
*4.21(检查 SSN)编写一个程序,提示用户输入一个社保号码,它的格式是DDD-DD-DDDD,其中D是一个数字。你的程序应该判断输入是否合法。
下面是一个运行示例:
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*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 -
参考代码:
package chapter04;
import java.util.*;
public class Code_21 {
public static void main(String[] args){
String ssnString;
System.out.print("Enter a SSN: ");
Scanner input = new Scanner(System.in);
ssnString = input.nextLine();
if(ssnString.length() == 11)
{
if(Character.isDigit(ssnString.charAt(0))
&& Character.isDigit(ssnString.charAt(1))
&& Character.isDigit(ssnString.charAt(2))
&& ssnString.charAt(3) == '-'
&& Character.isDigit(ssnString.charAt(4))
&& Character.isDigit(ssnString.charAt(5))
&& ssnString.charAt(6) == '-'
&& Character.isDigit(ssnString.charAt(7))
&& Character.isDigit(ssnString.charAt(8))
&& Character.isDigit(ssnString.charAt(9))
&& Character.isDigit(ssnString.charAt(10)))
System.out.println(ssnString + " is a valid social security number");
else
System.out.println(ssnString + " is an invalid social security number");
}
else
System.out.println(ssnString + " is an invalid social security number");
input.close();
}
}
- 结果显示:
Enter a SSN: 232-23-5435
232-23-5435 is a valid social security number
Process finished with exit code 0