使用java编写一段代码实现校验身份号功能
时间: 2024-06-10 21:06:23 浏览: 12
好的,我可以回答您的问题。以下是一个使用Java编写的身份证号码验证程序:
```
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IDNumberValidator {
// 正则表达式
private static final Pattern PATTERN = Pattern.compile("[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\\d|3[0-1])\\d{3}[0-9Xx]");
public static boolean validate(String idNumber) {
// 验证身份证号码格式是否正确
Matcher matcher = PATTERN.matcher(idNumber);
if (!matcher.matches()) {
return false;
}
// 验证身份证号码的校验码是否正确
char[] idChars = idNumber.toCharArray();
int sum = 0;
for (int i = 0; i < idChars.length - 1; i++) {
int idChar = idChars[i] - '0';
sum += idChar * (Math.pow(2, 17 - i) % 11);
}
int checkCode = (12 - (sum % 11)) % 11;
char lastChar = idChars[idChars.length - 1];
if (lastChar == 'X' || lastChar == 'x') {
return checkCode == 10;
} else {
return checkCode == (lastChar - '0');
}
}
}
```
使用方法如下:
```
String idNumber = "110101199003077156";
boolean isValid = IDNumberValidator.validate(idNumber);
if (isValid) {
System.out.println(idNumber + " 是有效的身份证号码");
} else {
System.out.println(idNumber + " 不是有效的身份证号码");
}
```
以上代码可以验证身份证号码的格式和校验码是否正确,如果验证通过,则返回 `true`,否则返回 `false`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)