1. 程式人生 > >15位身份證號碼轉換成18位身份證號碼(java程式碼)

15位身份證號碼轉換成18位身份證號碼(java程式碼)

步驟:1. 兩位年份填充為四位;2. 生成最後一位校驗位;

程式碼如下:

package com.mingo.common;

import java.util.Scanner;

public class IDcard15bitTo18bit {

    public static String[] trans15bitTo18bit(String[] input){
        String[] result = new String[18];
        for(int i=0;i<input.length;i++){
            if(i<=5){
                result[i] = input[i];
            }else
{ result[i+2] = input[i]; } } //年份最後兩位小於17,年份為20XX,否則為19XX if(Integer.valueOf(input[6])<=1&&Integer.valueOf(input[7])<=7){ result[6]="2"; result[7]="0"; }else{ result[6]="1"; result[7
]="9"; } //計算最後一位 String[] xs = {"7","9","10","5","8","4","2","1","6","3","7","9","10","5","8","4","2"}; //前十七位乘以係數[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+= Integer.valueOf(result[i]) * Integer.valueOf(xs[i]); } //對11求餘,的餘數 0 - 10
int rod = sum % 11; //所得餘數對映到對應數字即可 if(rod==0){ result[17] = "1"; }else if(rod==1){ result[17] = "0"; }else if(rod==2){ result[17] = "X"; }else if(rod==3){ result[17] = "9"; }else if(rod==4){ result[17] = "8"; }else if(rod==5){ result[17] = "7"; }else if(rod==6){ result[17] = "6"; }else if(rod==7){ result[17] = "5"; }else if(rod==8){ result[17] = "4"; }else if(rod==9){ result[17] = "3"; }else if(rod==10){ result[17] = "2";} return result; } public static void main(String[] args) { //建立輸入物件 Scanner sc=new Scanner(System.in); //獲取使用者輸入的字串 String str=""; System.out.print("請輸入您的15位身份證號:"); str=sc.nextLine(); System.out.println("您輸入的15位身份證號為:"+str); if(str.length()==15){ String[] input = str.split(""); String[] result = trans15bitTo18bit(input); System.out.print("您的18位身份證號是:"); for(String c:result){ System.out.print(c); } }else{ System.out.println("不符合格式的身份證號!"); } } }