Skip to content

Instantly share code, notes, and snippets.

@HabaCo
Last active August 29, 2015 14:02
Show Gist options
  • Save HabaCo/3edf5c0271f73056fd60 to your computer and use it in GitHub Desktop.
Save HabaCo/3edf5c0271f73056fd60 to your computer and use it in GitHub Desktop.
讀檔&身份證驗證&排序
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
// 身份證驗證
public class Q940306 {
public static String sample = "ABCDEFGHJKLMNPQRSTUVXYWZIO";
public static void main(String[] args) throws IOException{
String fileName = "940306.SM";
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String s;
// 先讀檔一次計算資料數量
int n=0;
while ((s=br.readLine())!=null && s.length()>0)
n++;
// 重新開檔(使檔案指標回到檔頭)
fr.close();
fr = new FileReader(fileName);
br = new BufferedReader(fr);
// 儲存每一筆身分證資訊的二維陣列
String[][] data = new String[n][4];
// 將檔案所讀到的資料放入 data[][]
// eg..
// ID Name Sex Errmsg
// [0] [1] [2] [3]
// data[0] B12X767544 ISAAC M FORMAT ERROR
// data[1] F222490168 DONA F
// data[2] 221930843 ALICE M SEX CODE ERROR
// ..
for (int i=0;(s=br.readLine())!=null && s.length()>0;i++){
String[] tmp = s.split(","); // [0]ID [1]Name [2]Sex
data[i][0] = tmp[0];
data[i][1] = tmp[1];
data[i][2] = tmp[2];
data[i][3] = idCheck(tmp[0],tmp[2]); // [3]Errmsg
}
fr.close();
// 排序 (選擇排序)
for (int i=0; i<n; i++){ // 資料筆數 (n)
for (int j=i+1; j<n; j++){ // 資料筆數 (n)
for (int l=0; l<data[i][0].length(); ) // 比較身分證的每一個位數 (10)
if (data[i][0].charAt(l) == data[j][0].charAt(l)) // 若當前字元大小相等則比下一個
l++;
else if (data[i][0].charAt(l) > data[j][0].charAt(l)){ // 將較小的身分證往前交換並回到 loop j
exChange(data[i],data[j]);
break;
}
else break; // 若以上皆否 (已排序狀態) 則跳出
}
}
// Print
for(String[] s1: data){
for(String s2: s1)
System.out.print(s2+"\t");
System.out.println();
}
}
// 身分驗證
public static String idCheck(String id, String sex){
int sum=0;
char[] tmp = id.toCharArray();
sex = sex.toUpperCase();
if (sample.indexOf(tmp[0])==-1 || (tmp[1] != '1' && tmp[1] != '2'))
return "FORMAT ERROR ";
if ((sex.charAt(0)=='M' && tmp[1] != '1') || (sex.charAt(0)=='F' && tmp[1] != '2'))
return "SEX CODE ERROR";
sum+=sample.indexOf(tmp[0])+10;
sum = sum/10+(sum%10)*9;
for (int i=1; i<9; i++){
if (tmp[i]<'0' || tmp[i]>'9')
return "FORMAT ERROR ";
else
sum+=Integer.parseInt(tmp[i]+"")*(9-i);
}
if ((10-sum%10)%10 != tmp[9]-48)
return "CHECK SUM ERROR";
return "";
}
// SWAP 陣列
public static void exChange(String[] s1, String[] s2){
for (int i=0; i<s1.length; i++){ // 將兩個陣列中所有的元素[0,1 .. n]都交換
String t = s1[i];
s1[i] = s2[i];
s2[i] = t;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment