看了http://demo.tc/view.aspx?id=398這篇文章有感而發寫出Java版本, 以後應該有機會用到。
信用卡校驗規則為:
1.必須是十六個數字.
2.由左至右取出奇數位數字乘2, 如果大於9則減去9.
3.合併奇數位與偶數位每一個數字總合必須能夠被10整除.
4.開頭第一個字元為4則是Visa, 頭兩個字元大於50則為Master.
注意一下Java char轉int 不可以用(int)char強制轉, 否則會變成ascii code, 請使用Character的digit(char ch, int radix).我們要轉十進位數字所以radix填10.
The Character class wraps a value of the primitive type char in an object.
digit(char ch, int radix) Returns the numeric value of the character ch in the specified radix.
Sample Code:
public static String checkCreditCard(String cardNo) { String result = "Wrong card number!!"; try { // length validation must bigger than sixteen. int length = cardNo.length(); if (length == 16) { String type = ""; if (cardNo.substring(0, 2).compareTo("50") >= 0) { type = "Master"; } else if (cardNo.substring(0, 1).equals("4") == true) { type = "Visa"; } // separate the card number. char[] sepCard = cardNo.toCharArray(); // create a new array. int[] newCard = new int[16]; for (int i = 0; i < sepCard.length; i++) { if ((i + 1) % 2 == 0) { newCard[i] = Character.digit(sepCard[i], 10); } else { newCard[i] = Character.digit(sepCard[i], 10) * 2; if (newCard[i] > 9) newCard[i] -= 9; } } int sum = 0; for (int i = 0; i < newCard.length; i++) { sum += newCard[i]; } if (sum % 10 == 0) result = type + " card."; } } catch (Exception ex) { ex.printStackTrace(); } return result; }
沒有留言:
張貼留言