gpt4 book ai didi

java - 日期的 boolean 编码

转载 作者:行者123 更新时间:2023-12-02 07:40:53 26 4
gpt4 key购买 nike

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) {
day = enteredDay;
}

public void setMonth(int month) {
month = enteredMonth;
}

public void setYear(int year) {
year = enteredYear;
}

public String toString() {
return getDay() + "/" + getMonth() + "/" + getYear();
}

public boolean isEarlier(Date) {
if (enteredDay.getDay() < day) {
return true;
} else {
return false;
}
}
}

我无法让最后一种方法发挥作用。它必须是 boolean 值,如果日期早于它,则返回 true。我的问题(至少据我所知)是弄清楚在“<”运算符的两侧写什么。任何有关代码其余部分的反馈将不胜感激。

最佳答案

我会遍历年、月、日,依次进行比较,直到找到严格早或晚的一对。

使用比较器,尤其是在 Java 8 简洁的语法中,可以为您节省大量样板代码:

public boolean isEarlier(Date other) {
return Comparator.comparingInt(Date::getYear)
.thenComparingInt(Date::getMoth)
.thenComparingInt(Date::getDay)
.compare(this, other) < 0;
}

编辑:
要回答评论中的问题,您当然可以手动比较每个字段:

public boolean isEarlier(Date other) {
if (getYear() < other.getYear()) {
return true;
} else if (getYear() > other.getYear()) {
return false;
}

// If we reached here, both dates' years are equal

if (getMonth() < other.getMonth()) {
return true;
} else if (getMonth() > other.getMonth()) {
return false;
}

// If we reached here, both dates' years and months are equal

return getDay() < other.getDay();
}

这当然可以压缩为单个 boolean 语句,尽管它是否更优雅或不太优雅在某种程度上取决于情人的眼睛(括号不是严格需要的,但恕我直言,它们使代码更清晰):

public boolean isEarlier(Date other) {
return (getYear() < other.getYear()) ||
(getYear() == other.getYear() &&
getMonth() < other.getMonth()) ||
(getYear() == other.getYear() &&
getMonth() == other.getMonth() &&
getDay() < other.getDay());
}

关于java - 日期的 boolean 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50442410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com