身份证号码判断性别 public class Test01 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //1) 键盘输入身份证号 System.out.println("请输入身份证号"); String personId = sc.next(); //370211199011234557 //获适当前年 Calendar calendar = Calendar.getInstance(); int currentYear = calendar.get(Calendar.YEAR); //身份证号规则是: 第一位数字不克不及是0, 中间有16位数字, 最初一位是数字或者X String pattern = "[1-9]\\d{16}[0-9X]"; while (true) { //当输入身份证号字符串不契合身份证号格局需要从头输入 if (!personId.matches(pattern)) { System.out.println("身份证号格局不准确 , 请从头 输入"); personId = sc.next(); continue; //完毕本次轮回 } //判断年份的合理性 String yearStr = personId.substring(6, 10); //"1990" int year = Integer.parseInt(yearStr); //1990 if ( year < 1900 || year > currentYear - 18 ){ System.out.println(year + "年份不合理, 请从头输入:"); personId = sc.next(); continue; //完毕本次轮回 } //判断月份的合理性 String monthStr = personId.substring(10, 12); //"11" int month = Integer.parseInt( monthStr); //11 if ( month < 1 || month > 12 ){ System.out.println(month + "月份不合理, 请从头输入:"); personId = sc.next(); continue; //完毕本次轮回 } //判断日的合理性 String dayStr = personId.substring(12, 14); //"22" int day = Integer.parseInt(dayStr); //22 if ( day < 1 || day > getMonthDays(year,month) ){ System.out.println(day + "天数不合理, 请从头输入:"); personId = sc.next(); continue; //完毕本次轮回 } //年月日合理,打印出生日期 System.out.println("出生日期:" + yearStr + "年" + monthStr + "月" + dayStr + "日"); //判断性别 char cc = personId.charAt(16); //5 //0字符码值是48, 1字符的码值是49, 即数字的奇偶性与码值奇偶性是婚配的 System.out.println(cc % 2 == 0 ? "女" : "男"); break; } } //定义办法,返回指定月份的天数 private static int getMonthDays(int year, int month) { switch ( month ){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: //若是闰年29天,不然28天 return isLeap( year )? 29 : 28; } return 0; } private static boolean isLeap( int year ){ return year % 4 ==0 && year % 100 != 0 || year % 400 == 0 ; } }
0