首页 > 解决方案 > 如何使用构造函数的出生日期计算年龄?

问题描述

 // main 
public class Application {
     public static void main(String[] args)  {

        StudentRepository myStudent = new StudentRepository();
    myStudent.addStudent("St","Rt","0742", "1993.03.04", PersonGender.MALE, "1930303");
    myStudent.addStudent("Sr","Ro","0742", "1994.03.04", PersonGender.MALE, "1940304");
    myStudent.addStudent("Se","Rb","0742", "1995.03.04", PersonGender.MALE, "1950305");
    myStudent.addStudent("Sm","Re","0742", "1996.03.04", PersonGender.MALE, "1950306");
    myStudent.deleteStudent("Stumer","Robert","0742", "1992.03.04", PersonGender.MALE, "null");
    myStudent.deleteStudent("Sr","Ro","0742", "1994.03.04", PersonGender.MALE, "1940304");
    myStudent.displayStudents();
    myStudent.calculateAge();// not working
 }
}


 // class StudentRepository
  public class StudentRepository  {


private final Map<String, Student> students = new HashMap<>();


public void addStudent(String firstName, String lastName, String phoneNumber, String birthDate, PersonGender gender, String id) {
    Student student = new Student(firstName, lastName, phoneNumber, birthDate,  gender, id);

    if (students.containsKey(id)) {
        throw new IllegalArgumentException("Student already exist!");
    }
   students.put(id, student);
}

public void deleteStudent(String firstName, String lastName, String phoneNumber, String birthDate, PersonGender gender, String id)  {
    Student student = new Student(firstName, lastName, phoneNumber, birthDate,  gender, id);

    if (id == null) {
        throw new NullPointerException("ID is null");
    }

    if (students.containsKey(id)) {
        students.remove(id);
    }
    else {
        throw new NullPointerException("The student does not exist");
    }

}

public void displayStudents() {
    System.out.println("The student list:");
    displayCollection(students.values());
}

private <T> void displayCollection(Collection<T> collection) {
    for (T item : collection) {
        System.out.println(item);
    }
}


public  int calculateAge(LocalDate birthDate) {
    String birthday = "1993.03.04";
    birthDate = LocalDate.parse(birthday, 
    DateTimeFormatter.ofPattern("yyyy.MM.dd"));
    int ageInYears = calculateAge(birthDate);
    Period period = Period.between(birthDate, LocalDate.now());
    return period.getYears();
}

// class Student
public  class Student {

private final String firstName;
private final String lastName;
private final String phoneNumber;
private final String birthDate;
private final PersonGender gender;
private final String id;



public Student(String firstName, String lastName, String phoneNumber, String birthDate, PersonGender gender, String id) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.phoneNumber = phoneNumber;
    this.birthDate = birthDate;
    this.gender = gender;
    this.id = id;

}



@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Student student = (Student) o;
    return Objects.equals(firstName, student.firstName) &&
            Objects.equals(lastName, student.lastName) &&
            Objects.equals(phoneNumber, student.phoneNumber) &&
            Objects.equals(birthDate, student.birthDate) &&
            gender == student.gender &&
            Objects.equals(id, student.id);
}

@Override
public int hashCode() {
    return Objects.hash(firstName, lastName, phoneNumber, birthDate, gender, id);
}

@Override
public String toString() {
    return "Student{" +
            "firstName='" + firstName + '\'' +
            ", lastName='" + lastName + '\'' +
            ", phoneNumber='" + phoneNumber + '\'' +
            ", birthDate='" + birthDate + '\'' +
            ", gender=" + gender +
            ", id='" + id + '\'' +
            '}';
}

}

日期代码是构造函数的第四个参数,下面是我为计算年龄而实现的方法。要求是:检索年龄为 X 的所有学生(必须计算每个学生的年龄,而不是存储在字段中)。* 例外:年龄为负数。我这一刻我正在学习JAva,欢迎任何改进建议

标签: java

解决方案


好吧,如果您能够/允许使用java.time,您可以在一个声明中计算一个人的年龄,通过他/她的出生日期/只需几行。

看这个例子:

public static int getAgeInFullYears(LocalDate birthDate) {
    Period period = Period.between(birthDate, LocalDate.now());
    return period.getYears();
}

您必须将出生日期作为 的实例传递,您可以在之前从 a (格式化为问题代码中的那些)java.time.LocalDate解析它,请参阅此示例用法:String

public static void main(String[] args) {
    // provide the date of birth as String
    String birthday = "1993.03.04";
    // parse it to a LocalDate using a formatter that parses the String format
    LocalDate birthDate = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy.MM.dd"));
    // then calculate the years using the method
    int ageInYears = getAgeInFullYears(birthDate);
    // and print some result statment
    System.out.printf("The person is %d years old (date of calculation %s)",
                    ageInYears,
                    LocalDate.now());
}

输出将是这样的:

The person is 27 years old (date of calculation 2020-06-11)

编辑:

修改当前代码的最简单方法是添加计算方法,该方法首先从String属性中解析日期,然后使用合适的类计算年龄。
你可以这样做:

class Student {
    private String birthDate;

    (...) // irrelevant code omitted for brevity

    public int getAgeInYears() {
        // parse the date of birth from the String attribute
        LocalDate dateOfBirth = LocalDate.parse(birthDate,
                                            DateTimeFormatter.ofPattern("yyyy.MM.dd"));
        // then calculate the age in years at date of execution
        return Period.between(dateOfBirth, LocalDate.now()).getYears();
    }
}

推荐阅读