1 package com.jdk7.chapter5;
2
3 /**
4 * 仅能校验15位或18位身份证号的校验码
5 * @author Administrator
6 *
7 */
8 public class IDCardTest {
9 private static final int[] weigth =
new int[] {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2
};
10 private static final int[] checkCode =
new int[] {1,0,'x',9,8,7,6,5,4,3,2
};
11
12 /**
13 * 如果是15位身份证号则升级为18位身份证
14 * 然后统一对18为身份证号最后一位进行校验,取18位身份证号最后一位和前17位通过公式计算的结果比较
15 * @param str
16 * @return
17 */
18 public static boolean isIDcard(String str){
19 if(str.length()==15
){
20 str =
IDCardTest.updateID(str);
21 }
22 if(str.length()!=18
){
23 return false;
24 }
25 String code = str.substring(17, 18
);
26 if(code.equals(getCheck(str))){
27 return true;
28 }
29 return false;
30 }
31
32 /**
33 * 1.15位的身份证号在出生年份前+19,组成17为数
34 * 2.再获取17位数的验证码
35 * 3.17位数+验证码组成18位的身份号
36 * @param fifteenstr
37 * @return
38 */
39 public static String updateID(String fifteenstr){
40 StringBuffer sb =
new StringBuffer();
41 String eigthteen = fifteenstr.substring(0, 6
);
42 eigthteen = (sb.append(eigthteen).append("19").append(fifteenstr.substring(6, 15
))).toString();
43 eigthteen = eigthteen +
getCheck(eigthteen);
44 return eigthteen;
45 }
46
47 /**
48 * 对参数前17位进行校验码计算:
49 * 18位身份证号由17位数字体+1位校验码组成,排列从左至右依次为:6位地区代码+8位出生日期+3位顺序码+1为校验码
50 * 3位顺序码为同一天出生序号,奇数为男性,偶数为女性
51 * 身份证校验码的关键技术为:
52 * 对前17数字本体码和加权求和,S=Sum(Ai*Wi),i=0...16,Ai表示第i个位置上身份证号码对应的数字,Wi表示第i个位置上加权因子对应值
53 * 加权因子从0到16的值分别为7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2
54 * 对S取模,Y=mod(S,11)
55 * 通过Y获取校验码,Y对应的值即为校验码,对应关系为如下:
56 * <0,1>、<1,0>、<2,x>、<3,9>、<4,8>、<5,7>、<6,6>、<7,5>、<8,4>、<9,3>、<10,2>
57 * 对应关系中前者为Y,后者为校验码
58 * @param str
59 * @return
60 */
61 public static String getCheck(String str){
62
63 if(str.length()==18
){
64 str = str.substring(0, 17
);
65 }
66 int Y = 0
;
67 if(str.length()==17
){
68 int[] a =
new int[str.length()];
69 int sum = 0
;
70 for(
int i=0;i<str.length();i++
){
71 a[i] = Integer.parseInt(str.substring(i, i+1
));
72 sum = sum + (a[i] *
weigth[i]);
73 }
74 Y = sum % 11
;
75 }
76 return (Y==2)?"x"
:String.valueOf(checkCode[Y]);
77 }
78
79 public static void main(String[] args) {
80 String id = "110105198709191369"
;
81 // String id = "110105870919136";
82 System.out.println(id+"校验码是否通过?"+
IDCardTest.isIDcard(id));
83 }
84 }
85
86 执行结果:
87 110105198709191369校验码是否通过?
true
转载于:https://www.cnblogs.com/celine/p/8463409.html
相关资源:数据结构—成绩单生成器