java 18位和15位身份证号校验
时间: 2024-03-20 21:39:36 浏览: 73
好的,以下是Java实现的18位和15位身份证号校验的方法:
1. 18位身份证号校验:
```java
public static boolean isIDCard18(String idCard) {
if (idCard == null || idCard.length() != 18) {
return false;
}
char[] chars = idCard.toCharArray();
int[] ints = new int[17];
for (int i = 0; i < 17; i++) {
ints[i] = chars[i] - '0';
if (ints[i] < 0 || ints[i] > 9) {
return false;
}
}
int[] coefficients = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
int sum = 0;
for (int i = 0; i < 17; i++) {
sum += coefficients[i] * ints[i];
}
int remainder = sum % 11;
String[] codes = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
return codes[remainder].equals(String.valueOf(chars[17]));
}
```
2. 15位身份证号校验:
```java
public static boolean isIDCard15(String idCard) {
if (idCard == null || idCard.length() != 15) {
return false;
}
char[] chars = idCard.toCharArray();
int[] ints = new int[15];
for (int i = 0; i < 15; i++) {
ints[i] = chars[i] - '0';
if (ints[i] < 0 || ints[i] > 9) {
return false;
}
}
int[] coefficients = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8};
int sum = 0;
for (int i = 0; i < 15; i++) {
sum += coefficients[i] * ints[i];
}
int remainder = sum % 11;
String[] codes = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
return codes[remainder].equals(String.valueOf(chars[14]));
}
```
这两个方法都是基于身份证号的校验码计算方法,校验码的计算方式都是一样的。
阅读全文