在我的一个构造函数中,我有:
public Author(String firstName, String lastName, String middleName, int yearBorn,
int monthBorn, int dayBorn, int yearDied, int monthDied, int dayDied,
String pseudonymFirstName, String pseudonymLastName, String pseudonymMiddleName ){
name = new Name(firstName,lastName,middleName);
born = new Date(yearBorn, monthBorn, dayBorn);
died = new Date(yearDied, monthDied, dayDied);
if((pseudonymFirstName == null) && (pseudonymLastName == null) && (pseudonymMiddleName == null)){
pseudonym = null;
}else{
pseudonym = new Name(pseudonymFirstName,pseudonymLastName,pseudonymMiddleName);
}
}
此构造函数调用其他类中的方法来存储Author
类的值。
现在我想制作一个方法,从yearBorn
中减去current year
的值,给我一个作者的年龄
到目前为止,我的方法看起来像:
public int getAgeYearsOfAuthor(){
return CURRENT_YEAR - (WHAT DO I PUT HERE?????);
}
如何在构造函数中提取yearBorn
值(这是一个int)形式:born = new Date(yearBorn, monthBorn, dayBorn);
?
答案 0 :(得分:0)
你可以试试这个方法
public int getAgeYearsOfAuthor(){
return CURRENT_YEAR -(born.getYear)
}
但要小心,如果你使用JAVA中的日期它是构造函数,当你设置年份它将为你的变量添加1900
答案 1 :(得分:0)
试试这个:
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(born, now);
确保您的born Date
是正确的LocalDate()
答案 2 :(得分:0)
在java8中你可以这样做:
final LocalDate now = LocalDate.now();
final LocalDate birt = LocalDate.of(1980, Month.DECEMBER, 10);
final Period p = Period.between(birt, now);
System.out.println("You are " + p.getYears() + " years old.");