Java is the core code for verifying the correctness of a bank card
- 2020-06-01 09:42:02
- OfStack
More talk, less code:
/**
* Verify bank card number
*
* @param cardId
* @return
*/
public static boolean checkBankCard(String cardId) {
char bit = getBankCardCheckCode(cardId
.substring(0, cardId.length() - 1));
return cardId.charAt(cardId.length() - 1) == bit;
}
/**
* Bank card Numbers that do not contain checksum bits are used Luhm The calibration algorithm obtains the calibration bit
*
* @param nonCheckCodeCardId
* @return
*/
public static char getBankCardCheckCode(String nonCheckCodeCardId) {
int cardLenth = nonCheckCodeCardId.trim().length();
if (nonCheckCodeCardId == null || cardLenth == 0
|| !nonCheckCodeCardId.matches("\\d+")) {
throw new IllegalArgumentException(" It's not the card number !");
}
char[] chs = nonCheckCodeCardId.trim().toCharArray();
int luhmSum = 0;
for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
int k = chs[i] - '0';
if (j % 2 == 0) {
k *= 2;
k = k / 10 + k % 10;
}
luhmSum += k;
}
return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
}
Feel this copy past can... So I didn't go into it. It felt like a waste of time.