只验证了18位
public static boolean isValid(String str) {
if (str == null || str.length() != 18) {
return false;
}
int WEIGHTS[] = {
7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2
};
char CHECK[] = {
'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'
};
int sum = 0;
for (int index = 0; index < 17; index++) {
if (str.charAt(index) < '0' || str.charAt(index) > '9') {
return false;
}
sum += str.charAt(index) * WEIGHTS[index];
}
if (CHECK[sum % 11] != Character.toUpperCase(str.charAt(str.length() - 1))) {
return false;
}
return true;
}
public static boolean isValid(String str) {
if (str == null || str.length() != 18) {
return false;
}
int WEIGHTS[] = {
7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2
};
char CHECK[] = {
'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'
};
int sum = 0;
for (int index = 0; index < 17; index++) {
if (str.charAt(index) < '0' || str.charAt(index) > '9') {
return false;
}
sum += str.charAt(index) * WEIGHTS[index];
}
if (CHECK[sum % 11] != Character.toUpperCase(str.charAt(str.length() - 1))) {
return false;
}
return true;
}
public static boolean isValid(String str) { if (str == null || str.length() != 18) { return false; } int WEIGHTS[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; char CHECK[] = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' }; int sum = 0; for (int index = 0; index < 17; index++) { if (str.charAt(index) < '0' || str.charAt(index) > '9') { return false; } sum += str.charAt(index) * WEIGHTS[index]; } if (CHECK[sum % 11] != Character.toUpperCase(str.charAt(str.length() - 1))) { return false; } return true; }