
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/**
* 驗證身份證號碼是否合法
*
* @author xhh 認為代碼還能簡化
*/
public class Main{
// 判斷前17位數是否為數字
public static boolean isNum(String ex) {
if (ex.matches("\\d+")) {
return true;
} else {
return false;
}
}
// 判斷最后一位數是否為數字或小寫字母
public static boolean isNumOrLower(char last) {
if (Character.isDigit(last) || (last >= 'a' && last <= 'z')) {
return true;
} else {
return false;
}
}
// 判斷日期是否合法
public static boolean isLegal(String birth) {
// 准備模板,從字符串中提取出日期數字
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
try {
format.setLenient(false);
format.parse(birth);
return true;
} catch (Exception e) {
return false;
}
}
// 校驗碼檢查最后一位
public static boolean checkLast(String ex, char last) {
// 將前面的身份證號碼17位數分別乘以不同的系數
// 從第一位到第十七位的系數分別為:7-9-10-5-8-4-2-1-6-3-7-9-10-5-8-4-2
// 將系數存入int數組中,不可修改
final int[] coeffcients = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
// 將17位數轉化為char數組,再轉換成int數組
char[] cArray = ex.toCharArray();
int[] iArray = new int[cArray.length];
int sum = 0; // 將這17位數字和系數相乘的結果相加
int remain = 0; // 用加出來和除以11,取余
// 注意:數字多就不適合使用這種方法
for (int i = 0; i < iArray.length; i++) {
iArray[i] = Integer.parseInt(String.valueOf(cArray[i]));
sum += iArray[i] * coeffcients[i];
}
remain = sum % 11;
// 余數只可能有0-1-2-3-4-5-6-7-8-9-10這11個數字
// 其分別對應的最后一位身份證的號碼為1-0-X-9-8-7-6-5-4-3-2。
final String[] s = { "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2" };
// 判斷是否和輸入的身份證尾數相同
if (s[remain].equals(String.valueOf(last))) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// 輸入18位身份證
Scanner in = new Scanner(System.in);
String id = null;
// 判斷是否輸入
if (in.hasNext()) {
id = in.next();
}
// 判斷是否18位
if (id.length() == 18) {
// 獲取前17位數
String exString = id.substring(0, 17);
// 獲取最后一位數
char lastChar = id.charAt(17);
// 獲取生日
String birth = id.substring(6, 14);
// 判斷身份證是否合法
if (isNum(exString) && isNumOrLower(lastChar) && isLegal(birth) && checkLast(exString, lastChar)) {
// 准備模板,從字符串中提取出日期數字
SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
// 准備模板,將提取后的日期數字變為指定的格式
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format1.parse(birth);
System.out.println(format2.format(date)); // 輸出有效日期
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("0000-00-00");
}
} else {
System.out.println("0000-00-00");
}
}
}