创建CardUtil工具类
public class CardUtil {
/**
* 验证身份证真假
* @param carNumber 身份证号
* @return boolean*/
public static boolean isCard(String carNumber) {
//判断输入身份证号长度是否合法
if (carNumber.length() != 18) {
throw new RuntimeException("身份证长度不合法");//不合法 抛出一个异常
}
//校验身份证真假
int sum = 0;
int[] weight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};//将加权因子定义为数组
//遍历weight数组 求身份证前17项系数和
for (int i = 0; i < weight.length; i++) {
int n = carNumber.charAt(i) - 48;//获取 身份证对应数
int w = weight[i];
sum += w * n;
}
//对11求余
int index = sum % 11;
//校验码
String m = "10X98765432";
//获取身份证最后一位进行比对
return m.charAt(index) == carNumber.charAt(17);
}
}
标签:carNumber,java,weight,int,sum,身份证号,校验,身份证
From: https://www.cnblogs.com/h-w-b/p/16962085.html