2013年1月5日 星期六

Java-驗證身分證的Method


--------------------------------------------------------------------------------------------------------
public class IDCheck {
 private int convert(char ch){
  ch =Character.toUpperCase(ch);
  switch(ch){
      case 'A': return 10;
      case 'B': return 11;
      case 'C': return 12;
      case 'D': return 13;
      case 'E': return 14;
      case 'F': return 15;
      case 'G': return 16;
      case 'H': return 17;
      case 'I': return 34;
      case 'J': return 18;
      case 'K': return 19;
      case 'L': return 20;
      case 'M': return 21;
      case 'N': return 22;
      case 'O': return 35;
      case 'P': return 23;
      case 'Q': return 24;
      case 'R': return 25;
      case 'S': return 26;
      case 'T': return 27;
      case 'U': return 28;
      case 'V': return 29;
      case 'W': return 32;
      case 'X': return 30;
      case 'Y': return 31;
      case 'Z': return 32;
  }
  return -100;
 }
 private boolean checkFormat(String id){
  if(id.length() !=10){
   System.out.println("長度不符合");
   return false;
  }
  for(int i=1; i<10; i++){
   char ch = id.charAt(i);
   if(!Character.isDigit(ch)){
    System.out.println("格式錯誤");
    return false;
   }
  }
  return true;
 }
 public boolean check(String id){
  if(!checkFormat(id)){
   return false;
  }
  char ch = id.charAt(0);
    int D0 = this.convert(ch);
 
   int D1 = Integer.parseInt(id.substring(1, 2));
   int D2 = Integer.parseInt(id.substring(2, 3));
   int D3 = Integer.parseInt(id.substring(3, 4));
   int D4 = Integer.parseInt(id.substring(4, 5));
   int D5 = Integer.parseInt(id.substring(5, 6));
   int D6 = Integer.parseInt(id.substring(6, 7));
   int D7 = Integer.parseInt(id.substring(7, 8));
   int D8 = Integer.parseInt(id.substring(8, 9));
   int D9 = Integer.parseInt(id.substring(9, 10));
   int X1 = D0/10;
   int X2 = D0%10;
   int Y = X1+ 9*X2+ 8*D1+ 7*D2+ 6*D3+ 5*D4+4*D5+ 3*D6+ 2*D7+ D8;
   int CheckCode = (10-(Y % 10)) % 10;
 
   if(CheckCode==D9) {
    return true;
   } else {
     return false;
   }
 }
}
--------------------------------------------------------------------------------------------------------

沒有留言:

張貼留言