java验证身份证号码合法性
时间: 2023-11-25 21:52:25 浏览: 161
以下是Java中验证身份证号码合法性的方法:
```java
public static boolean isValidIdCard(String idCard) {
if (idCard == null || idCard.length() != 18) {
return false;
}
char[] chars = idCard.toCharArray();
int[] ints = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
ints[i] = Integer.parseInt(chars[i] + "");
}
int sum = 0;
for (int i = 0; i < ints.length - 1; i++) {
sum += ints[i] * WEIGHTS[i];
}
int mod = sum % 11;
int checkCode = CHECK_CODES[mod];
return checkCode == ints[ints.length - 1];
}
private static final int[] WEIGHTS = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
private static final int[] CHECK_CODES = new int[]{1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2};
```
其中,`isValidIdCard`方法接收一个身份证号码字符串作为参数,返回一个布尔值,表示该身份证号码是否合法。如果身份证号码合法,返回`true`,否则返回`false`。
阅读全文