Date类isEarlier布尔方法故障排查及代码优化咨询
代码问题修复与优化建议
我帮你梳理下代码里的问题,一步步来修复和优化:
1. Setter方法的变量错误
你的三个set方法里都用到了未定义的变量(enteredDay、enteredMonth、enteredYear),这会直接导致编译失败。正确的写法是用this关键字区分类的实例变量和方法参数,把参数值赋值给实例变量:
public void setDay(int day) { this.day = day; // this.day指向类的实例变量,右边的day是方法传入的参数 } public void setMonth(int month) { this.month = month; } public void setYear(int year) { this.year = year; }
2. isEarlier方法的语法与逻辑错误
这个方法有两个核心问题:
- 参数未命名:
isEarlier(Date)必须给传入的Date对象起一个名称(比如otherDate),否则无法在方法内引用这个传入的日期 - 比较逻辑错误:判断日期早晚不能只对比“日”,要按照年→月→日的优先级依次比较,不然会出现类似「2024/1/30」被判断为早于「2023/12/31」的错误
修复后的isEarlier方法如下:
public boolean isEarlier(Date otherDate) { // 先比较年份:传入日期的年更小,直接判定更早 if (otherDate.getYear() < this.getYear()) { return true; } // 年份相等时,比较月份 else if (otherDate.getYear() == this.getYear()) { if (otherDate.getMonth() < this.getMonth()) { return true; } // 月份也相等时,最后比较日期 else if (otherDate.getMonth() == this.getMonth()) { return otherDate.getDay() < this.getDay(); } } // 所有条件都不满足,说明传入的日期不早于当前实例 return false; }
修复后的完整代码
class Date { private int day; private int month; private int year; public Date() { } public Date(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public int getDay() { return this.day; } public int getMonth() { return this.month; } public int getYear() { return this.year; } public void setDay(int day) { this.day = day; } public void setMonth(int month) { this.month = month; } public void setYear(int year) { this.year = year; } public String toString() { return getDay() + "/" + getMonth() + "/" + getYear(); } public boolean isEarlier(Date otherDate) { if (otherDate.getYear() < this.getYear()) { return true; } else if (otherDate.getYear() == this.getYear()) { if (otherDate.getMonth() < this.getMonth()) { return true; } else if (otherDate.getMonth() == this.getMonth()) { return otherDate.getDay() < this.getDay(); } } return false; } }
额外的小建议
- 可以给无参构造函数设置默认值,比如
this(1, 1, 2000),避免创建出0/0/0这种无效日期 - 进阶优化的话,可以在set方法里加入参数合法性校验,比如月份不能超过12、日期要对应月份的实际天数(这个需要额外的逻辑处理)
内容的提问来源于stack exchange,提问作者user9591229
相关产品推荐
相关产品推荐

