java隨機生成證件號

import java.text.SimpleDateFormat;
import java.util.*;

public class IdentityUtil {

    /**
     * 省、自治區、直轄市代碼
     */
    private static String provinces[] = { "11", "12", "13", "14", "15", "21", "22", "23",
            "31", "32", "33", "34", "35", "36", "37", "41", "42", "43",
            "44", "45", "46", "50", "51", "52", "53", "54", "61", "62",
            "63", "64", "65", "71", "81", "82" };

    /**
     * 地級市、盟、自治州代碼
     */
    private static String citys[] = { "01", "02", "03", "04", "05", "06", "07", "08",
            "09", "10", "21", "22", "23", "24", "25", "26", "27", "28" };

    /**
     * 縣、縣級市、區代碼
     */
    private static String countys[] = { "01", "02", "03", "04", "05", "06", "07", "08",
            "09", "10", "21", "22", "23", "24", "25", "26", "27", "28",
            "29", "30", "31", "32", "33", "34", "35", "36", "37", "38" };

    public static String getRandomID() {
        StringBuffer identityNo = new StringBuffer();

        // 隨機生成省、自治區、直轄市代碼 1-2
        identityNo.append(provinces[new Random().nextInt(provinces.length - 1)]);

        // 隨機生成地級市、盟、自治州代碼 3-4
        identityNo.append(citys[new Random().nextInt(citys.length - 1)]);

        // 隨機生成縣、縣級市、區代碼 5-6
        identityNo.append(countys[new Random().nextInt(countys.length - 1)]);

        // 隨機生成出生年月 7-14
        SimpleDateFormat dft = new SimpleDateFormat("yyyyMMdd");
        Date beginDate = new Date();
        Calendar date = Calendar.getInstance();
        date.setTime(beginDate);
        date.set(Calendar.DATE, date.get(Calendar.DATE) - new Random().nextInt(365 * 100));
        identityNo.append(dft.format(date.getTime()));

        // 隨機生成順序號 15-17
        String num = String.valueOf(System.currentTimeMillis());
        identityNo.append(num.substring(num.length()-3));

        // 生成校驗碼 18
        identityNo.append(getVerifyCode(identityNo));
        return identityNo.toString();
    }

    /**
     * 計算校驗碼
     * @param cardId
     * @return
     */
    private static char getVerifyCode(StringBuffer cardId) {
        char[] ValCodeArr = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        int[] Wi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        int tmp = 0;
        for (int i = 0; i < Wi.length; i++) {
            tmp += Integer.parseInt(String.valueOf(cardId.charAt(i))) * Wi[i];
        }
        return ValCodeArr[tmp % 11];
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章