身份证号码分析java
时间: 2023-11-04 20:51:35 浏览: 67
身份证号码是中国公民身份证的唯一标识符,它包含了个人的基本信息和身份信息。下面是一个简单的身份证号码分析的Java实现:
```java
import java.util.Calendar;
public class IDCardAnalyzer {
private String idCardNumber;
public IDCardAnalyzer(String idCardNumber) {
this.idCardNumber = idCardNumber;
}
// 获取性别
public String getGender() {
String gender = "";
int genderCode = Integer.parseInt(idCardNumber.substring(16, 17));
if (genderCode % 2 == 0) {
gender = "女";
} else {
gender = "男";
}
return gender;
}
// 获取出生日期
public String getBirthDate() {
String birthDate = "";
String year = idCardNumber.substring(6, 10);
String month = idCardNumber.substring(10, 12);
String day = idCardNumber.substring(12, 14);
birthDate = year + "-" + month + "-" + day;
return birthDate;
}
// 获取年龄
public int getAge() {
int age = 0;
Calendar cal = Calendar.getInstance();
int currentYear = cal.get(Calendar.YEAR);
int birthYear = Integer.parseInt(idCardNumber.substring(6, 10));
age = currentYear - birthYear;
return age;
}
// 判断是否为合法的身份证号码
public boolean isValid() {
boolean isValid = false;
if (idCardNumber.length() == 18) {
char[] chars = idCardNumber.toCharArray();
int[] weights = new int[] {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
char[] checkCodes = new char[] {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
int sum = 0;
for (int i = 0; i < 17; i++) {
sum += (chars[i] - '0') * weights[i];
}
char checkCode = checkCodes[sum % 11];
if (checkCode == chars[17]) {
isValid = true;
}
}
return isValid;
}
public static void main(String[] args) {
IDCardAnalyzer analyzer = new IDCardAnalyzer("身份证号码");
System.out.println("性别:" + analyzer.getGender());
System.out.println("出生日期:" + analyzer.getBirthDate());
System.out.println("年龄:" + analyzer.getAge());
System.out.println("是否合法:" + analyzer.isValid());
}
}
```
在上面的代码中,我们实现了以下功能:
- 获取身份证号码的性别
- 获取身份证号码的出生日期
- 获取身份证号码的年龄
- 判断身份证号码是否为合法的身份证号码
在实现过程中,我们使用了Java中的字符串操作和日期操作,以及身份证号码校验算法。
阅读全文