用戶代碼中校驗順序存在問題:
// 原代碼片段
if (province <= 00 || province >= 51) { ... } // 錯誤:省份代碼11-65,00和>=51邏輯反了
else if (year <= 1500 || year > 2015) { ... } // 年份上限硬編碼,2015年後失效
else if (month < 1 || month > 12) { ... }
else if (year%400==0 || year%4==0 && year%100!=0) { // 閏年判斷
if (month==2 && (day>29 || day<=0)) { ... }
}
else if (array[month] <= day || day <= 0) { ... } // 錯誤:應為 day > array[month]
else { 合法 }
11-65(含港澳台),代碼寫成province <= 00 || province >= 51導致合法省份(如11北京)被判定非法。day > maxDay判斷,maxDay根據月份和閏年動態計算。Calendar.getInstance().get(Calendar.YEAR)動態獲取當前年份。public static boolean isValidIdCard(String id) {
if (id == null || id.length() != 18) return false;
// 1. 省份碼
int province = Integer.parseInt(id.substring(0, 2));
if (province < 11 || province > 65) return false; // 簡化範圍
// 2. 出生日期
int year = Integer.parseInt(id.substring(6, 10));
int month = Integer.parseInt(id.substring(10, 12));
int day = Integer.parseInt(id.substring(12, 14));
int curYear = Calendar.getInstance().get(Calendar.YEAR);
if (year < 1900 || year > curYear) return false;
if (month < 1 || month > 12) return false;
// 3. 每月天數
int[] days = {0,31,28,31,30,31,30,31,31,30,31,30,31};
if (isLeapYear(year)) days[2] = 29;
if (day < 1 || day > days[month]) return false;
// 4. 校驗碼(省略,建議補全GB11643-1999標準算法)
return true;
}
private static boolean isLeapYear(int year) {
return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
}
province、year實際值。JOptionPane彈窗調試時,注意showInputDialog返回null(用戶點取消)需非空判斷。