zoukankan      html  css  js  c++  java
  • Java实现身份证号码校验

    二话不说,直接上代码。

    package hope.identitycodecheck.demo;

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    /**
    *
    * @author hp
    *
    * */
    public class IdentityCodeUtil {
    /**
    * 身份证号校验 (支持18位)
    *
    * */
    public static boolean checkIdentityCode(String identityCode) {
    if (!identityCode.matches("\d{17}(\d|x|X)$")) {
    return false;
    }
    Date d = new Date();
    DateFormat df = new SimpleDateFormat("yyyyMMdd");
    int year = Integer.parseInt(df.format(d));
    if (Integer.parseInt(identityCode.substring(6, 10)) < 1900 || Integer.parseInt(identityCode.substring(6, 10)) > year) {// 7-10位是出生年份,范围应该在1900-当前年份之间
    return false;
    }
    if (Integer.parseInt(identityCode.substring(10, 12)) < 1 || Integer.parseInt(identityCode.substring(10, 12)) > 12) {// 11-12位代表出生月份,范围应该在01-12之间
    return false;
    }
    if (Integer.parseInt(identityCode.substring(12, 14)) < 1 || Integer.parseInt(identityCode.substring(12, 14)) > 31) {// 13-14位是出生日期,范围应该在01-31之间
    return false;
    }
    // 校验第18位
    // S = Sum(Ai * Wi), i = 0, ... , 16 ,先对前17位数字的权求和
    // Ai:表示第i位置上的身份证号码数字值
    // Wi:表示第i位置上的加权因子
    // Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
    String[] tempA = identityCode.split("|");
    int[] a = new int[18];
    for (int i = 0; i < tempA.length - 2; i++) {
    a[i] = Integer.parseInt(tempA[i + 1]);
    }
    int[] w = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; // 加权因子
    int sum = 0;
    for (int i = 0; i < 17; i++) {
    sum = sum + a[i] * w[i];
    }
    // Y = mod(S, 11)
    // 通过模得到对应的校验码
    // Y: 0 1 2 3 4 5 6 7 8 9 10
    // 校验码: 1 0 X 9 8 7 6 5 4 3 2
    String[] v = { "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2" }; // 校验码
    int y = sum % 11;
    if (!v[y].equalsIgnoreCase(identityCode.substring(17))) {// 第18位校验码错误
    return false;
    }
    return true;
    }

    public static void main(String[] args) {
    System.out.println(checkIdentityCode("110110198001019719"));
    }
    }

  • 相关阅读:
    20191330雷清逸 学习笔记4
    sort
    20191330雷清逸 MyOD(选作,计入平时成绩)
    20191330雷清逸 Linux C语言编程基础(必做)
    20191330雷清逸 学习笔记3
    20191330雷清逸 学习笔记2
    无限的技能
    20191330 雷清逸 学习笔记1
    2021-2022-1-diocs-Linux系统编程第四周学习笔记
    Linux下man命令的使用
  • 原文地址:https://www.cnblogs.com/orionhp/p/6702544.html
Copyright © 2011-2022 走看看