一、实验目的
(1) 掌握异常处理程序的编写方法
(2) 掌握字符的处理方法
(3) 掌握数组的使用方法
二、实验内容
(1)编写应用程序,输入18位身份证号,判断输入的身份证号是否有效。
(2)当输入的身份证号前17位出现位数不足或不全是数字时,抛出自定义异常。程序捕获该异常,并提示用户错误信息,要求用户重新输入。
(3)用户验证完后,提示用户重复输入身份证号码进行新的验证。或者用户可以输入退出指令时,结束程序。
import java.math.BigDecimal;
import java.util.Scanner;
//自定义异常类继承Exception类
public class IDJudgeException extends Exception{
//构造方法
public IDJudgeException(String message){
//调用Exception有参的构造方法
super(message);
}
public static boolean Judge(String idcard)throws IDJudgeException{
//判断身份证号是否为空
if(idcard == null){
return false;
}
int len = 18;
//判断身份证长度是否为18位
if(idcard.length() != len){
//用throw关键字抛出自定义异常对象
throw new IDJudgeException("身份证号码不为18位!");
}
//利用substring方法截取前身份证17位
String idcard17 = idcard.substring(0, 17);
//进行判断
if(checkStrIsNum(idcard17) == false){
//用throw关键字抛出自定义异常对象
throw new IDJudgeException("输入的身份证前17位不正确!");
}else{
return true;
}
}
//利用BigDecimal判断是否位数字
//如果是数字,创建new Bigdecimal() 时肯定不会报错
public static boolean checkStrIsNum(String str) {
String bigStr;
try {
bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
System.out.println("前17位不全为数字!");
return false;
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入身份证号码:");
String idcard = in.nextLine();//接收用户输入
boolean result = false;
try {
Judge(idcard);//进行身份验证
result = Judge(idcard);
} catch (IDJudgeException e) {
//对捕获到的异常进行处理
System.out.println("捕获到的异常为:"+ e.getMessage());
//e.printStackTrace();
}
if(result == true){
System.out.println("身份校验正确,请输入0退出程序:");
int status = in.nextInt();
System.exit(status);
}
}
}