java身份证验证

package com.boventech.learning.test.card;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String cardString = "42011319920817113X";
		System.out.println(valiIdCard(cardString));
	}
	

	private static boolean valiIdCard(String idcard) {
	
                /* 系数 权值 */
		int[] quan = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8,
				4, 2 };
		int sum = 0;

		if (idcard.length() == 18) {

			// 循环quan数组取得每个位置对应的整数
			for (int i = 0; i < quan.length; i++) {
				// charAt(),获得字符串对应下标的字符
				sum += quan[i] * (idcard.charAt(i) - '0');
			}

           /* 相加的结果对11取余,用于匹配校验码 */
			int sum2 = sum % 11;

                       /* 
                        * 身份证校验码所有可能的取值 
                        * sum2 与 校验码对应的结果分别为
                        * sum2   < == >   校验码
                        *  0  < == > 1
                        *  1  < == > 0
                        *  2  < == > x
                        *  3  < == > 9
                        *  4  < == > 8
                        *  5  < == > 7
                        *  6  < == > 6
                        *  7  < == > 5
                        *  8  < == > 4
                        *  9  < == > 3
                        *  10 < == > 2
                        */
			char[] c = new char[] { '1', '0', 'X', '9', '8', '7', '6', '5',
					'4', '3', '2' };
			// 取出对应下标的字符,即为身份证第十八位
			char code = c[sum2];
			return code == idcard.charAt(17);
		}
		return false;

	}
	
}

你可能感兴趣的:(java身份证验证)