Java实现身份证验证代码

import java.lang.*;
 import java.io.*;
 import java.util.*;

public class CardID{
 private String cardNum;

public void setCardNum() {
 System.out.println("请输入身份证号码:");
 Scanner sc=new Scanner(System.in);
 cardNum=sc.nextLine();
 }
 public boolean lengthVerify() {
 return (cardNum.length()==18);
 }
 public boolean charVerify() {
 boolean flag=true;
 char ch=cardNum.charAt(17);
 if(!((ch>='0'&&ch<='9')||(ch=='X')||(ch=='x'))) {
 return false;
 }
 for(int i=0;i<=16;i++) {
 if(cardNum.charAt(i)<'0'||cardNum.charAt(i)>'9') {
 flag=false;
 break;
 }
 }
 return flag;
 }
 public boolean checkVerify() {
 String testNum=cardNum.substring(0,17)+"0";
 int sum=0,ai=0,wi=0;
 for(int i=18;i>=1;i--) {
 ai=testNum.charAt(18-i)-48;
 wi=(int)Math.pow(2,(i-1))%11;
 sum=sum+ai*wi;
 }
 int result=sum%11;
 char[] lastNum= {'1','0','X','9','8','7','6','5','4','3','2'};
 char[] lastNum1= {'1','0','x','9','8','7','6','5','4','3','2'};
 System.out.println("最后一位是:"+lastNum[result]);
 return cardNum.charAt(17)==lastNum[result]||cardNum.charAt(17)==lastNum1[result];

}
 public void output() {
 int year,month,day;
 year=Integer.parseInt(cardNum.substring(6,10));
 month=Integer.parseInt(cardNum.substring(10,12));
 day=Integer.parseInt(cardNum.substring(12,14));
 System.out.println("你的出生日期是:"+year+"-"+month+"-"+day);

Calendar cal=Calendar.getInstance();
 int nowYear=cal.get(Calendar.YEAR);
 int nowMonth=cal.get(Calendar.MONTH)+1;
 int nowDay=cal.get(Calendar.DAY_OF_MONTH);

int age=nowYear-year;
 int day2=nowDay-day;
 int month2=nowMonth-month;
 if(nowMonth<month) {
 age-=1;
 month2=12+month2;
 if(nowDay<day) { day2=30+day2; } else if(nowDay==day) { day2=0; }else { day2=30-day2; } }else if(nowMonth>month) {
 month2=nowMonth-month;
 if(nowDay<day) {
 day2=30+day2;
 }
 if(nowDay==day) {
 day=0;
 }
 else {
 day2=day2;
 }
 }
 else {
 month2=11;
 if(nowDay<day) {
 age-=1;
 day2=30+day2;
 }else if(nowDay==day) {
 System.out.println("生日快乐!");
 }
 else {
 day2=30-day2;
 }
 }
 System.out.println("你的年龄是:"+age+"岁"+month2+"个月"+day2+"天");

if(cardNum.charAt(16)%2==0) {
 System.out.println("女");
 }else {
 System.out.println("男");
 }
 }
 }

import java.lang.*;
 import java.io.*;
 import java.util.*;

public class CardIDDemo{
 public static void main(String args[]) {
 CardID id=new CardID();
 while(true) {
 id.setCardNum();
 if(!id.lengthVerify()) {
 System.out.println("身份证号码长度错误!");continue;
 }
 else if(!id.charVerify()) {
 System.out.println("身份证号码长度错误!");continue;
 }else if(!id.checkVerify()) {
 System.out.println("最后一位校验码错误!");continue;
 }else {
 id.output();
 }
 }
 }
 }