我也创建了一些类,MyDate
类保存某人的生日,并执行逻辑来获取两个日期之间的年份差异。 Person
保存某人的姓名和生日,您可以在其中检查某人是否比另一个人年长。
在MyDate
中,这就是我得到年份差异的方法:
public int differenceInYears(MyDate comparedDate) {
int difference = 0;
if (this.year > comparedDate.year) {
difference = this.year - comparedDate.year;
if (this.month == comparedDate.month && this.day < comparedDate.day
|| this.month < comparedDate.month) {
difference -= 1;
}
}
if (comparedDate.year > this.year) {
difference = comparedDate.year - this.year;
if (comparedDate.month == this.month && comparedDate.day < this.day
|| comparedDate.month < this.month) {
difference -= 1;
}
}
return difference;
}
在 Person
中,有两个相关的方法:
public int age() {
// you get the current day as follows:
//Calendar.getInstance().get(Calendar.DATE);
//Calendar.getInstance().get(Calendar.MONTH) + 1; // January is 0 so we add one
//Calendar.getInstance().get(Calendar.YEAR);
return calendar.differenceInYears(this.birthday);
}
calendar
是我在保存当前日期的类中启动的new MyDate
。
我使用的第二种方法检查一个人是否比另一个人年长:
public boolean olderThan(Person compared) {
if (this.age() > compared.age()) {
return true;
}
return false;
}
我不确定问题是什么,程序似乎运行良好,但是当我测试并让练习检查程序是否运行良好时,它给了我以下消息:
失败:PersonTest oldThanTest2
出生于 2009 年 12 月 31 日的 Helga 应该比出生于 2010 年 1 月 1 日的 Janika 年长
最佳答案
伪代码:
参数1日期1 参数2日期2
if (date1.year == date2.year){
if (date1.month == date2.month){
return date1.day > date2.day;
}
else
return date1.month > date2.month;
}
else
return date1.year > date2.year;
关于java - Java 的对象和类是我的逻辑缺陷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41707633/