验证身份证号码的合法性(对“清华大学出版社”出版的 “Java程序设计与应用开发(第2版)”中关于身份证号码合法性验证代码错误的修正)

import javax.swing.JOptionPane;//导入swing包中的JOptionPane类

public class Identity {  

public static void main(String[] args) {  

 String ID;  

 int year,month,day,lent,province;//身份证号码中对应的出生年月日及长度和省份

  ID=JOptionPane.showInputDialog("Input you ID");   

  //判断输入的号码长度是否合法,如果长度不合法,警告提示   

lent=ID.length();  

 if(lent!=18)   { 

 JOptionPane.showMessageDialog(null,"The length of you ID inputed is error!","Warning",0);    return ;   }  

     /**     

      * 省,直辖市代码表: { 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",   

      * 21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",    

      * 33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",    

      * 42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆", 

      * 51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",    

      * 63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}     

      */ 

  //从ID中获得省份,出生年月日

  province=Integer.parseInt(ID.substring(0,2));

  year=Integer.parseInt(ID.substring(6,10));

  month=Integer.parseInt(ID.substring(10,12));

  day=Integer.parseInt(ID.substring(12,14));   

int array[]={0,31,28,31,30,31,30,31,31,30,31,30,31};//定义数组array用于各月份最大天数的合法性判断

  if(province<=00||province>=51)  

  JOptionPane.showMessageDialog(null, "The province code inputed is error!","Warning",0);//判断省份是否在合法范围内

  else if(year<1900||year>=2013)    JOptionPane.showMessageDialog(null,"The year is error!","warning",0);//判断年份是否在合法范围内   

else if(month<1||month>12)    JOptionPane.showMessageDialog(null,"The month is error!","warning",0);//判断月份是否在合法范围内    

 //判断闰年日期是否合法  

 else if(year%400==0||(year%4==0&&year%100!=0))   {  

  if(month==2&&(day>29||day<=0))    

 JOptionPane.showMessageDialog(null,"The day is error!","warning",0); 

   else    

         JOptionPane.showMessageDialog(null,"The ID is right!\n"+ID,"Yes",JOptionPane.PLAIN_MESSAGE);

//以上红色部分为书中所缺少的部分

 }     

 //根据上面定义的数组判断非闰年情况下各月份生日是否合法   

else if(array[month]<=day||day<=0)    

JOptionPane.showMessageDialog(null,"The birthday is error!","warning",0);

  else   

       JOptionPane.showMessageDialog(null,"The ID is right!\n"+ID,"Yes",JOptionPane.PLAIN_MESSAGE);   

  }

 }

 

posted @ 2013-04-12 19:38  SKILL·NULL  阅读(419)  评论(0编辑  收藏  举报