[java]代码库
/**
* 身份证验证
* @author Administrator
*
*/
public class IDCard {
private final static int[] FACTOR = new int[]{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
/**
* 计算前17位身份证号乘以系数后的总和
* @param id17 前17位身份证号
* @return
*/
private static int sumFactor(String id17) {
if(id17==null || id17.trim().equals("")) {
return -1; //输入的身份证为空
}
int len = id17.length();
if(len!=17) {
return -3; //输入的身份证号码不为17位
}
int sum = 0;
for(int i=0; i<len; i++) {
sum += FACTOR[i] * Integer.parseInt(String.valueOf(id17.charAt(i)));
}
return sum;
}
/**
* 根据前17位身份证号,算出第18位的数字
* @param id17
* @return
*/
public static String getLastNumOfID(String id17) {
int sum = sumFactor(id17);
String res = "";
if(sum==-1) {
return "输入的身份证为空";
}else if(sum==-3) {
return "输入的身份证号码不为17位";
}else {
int mod = sum % 11;
switch(mod) {
case 0:
res = "1";
break;
case 1:
res = "0";
break;
case 2:
res = "X";
break;
case 3:
res = "9";
break;
case 4:
res = "8";
break;
case 5:
res = "7";
break;
case 6:
res = "6";
break;
case 7:
res = "5";
break;
case 8:
res = "4";
break;
case 9:
res = "3";
break;
case 10:
res = "2";
break;
default:
break;
}
}
return res;
}
/**
* 判断输入的身份证是否合法
* @param idNum 18位的身份证号
* @return
*/
public static boolean isCorrectID(String idNum) {
boolean flag = false;
if(idNum==null || idNum.trim().length()!=18) {
return flag;
}
String last = getLastNumOfID(idNum.substring(0, idNum.length()-1));
if(last.equals(String.valueOf(idNum.charAt(idNum.length()-1)))) {
flag = true;
}
return flag;
}
public static void main(String[] args) {
System.out.println(getLastNumOfID("36232319910420171"));
System.out.println(isCorrectID("362323199104201719"));
}
}