我的任务是:实现将日期移动一天的方法public void advance()。在本练习中,我们假设每个月都有30天。注意!在某些情况下,您需要更改月份和年份的值。
我已经这样做:
public class SimpleDate {
private int day;
private int month;
private int year;
public SimpleDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
@Override
public String toString() {
return this.day + "." + this.month + "." + this.year;
}
public boolean before(SimpleDate compared) {
if (this.year < compared.year) {
return true;
}
if (this.year == compared.year && this.month < compared.month) {
return true;
}
if (this.year == compared.year && this.month == compared.month &&
this.day < compared.day) {
return true;
}
return false;
}
public void advance(){
if(this.day<30){
this.day += 1;
}
if(this.day==30 && this.month==12){
this.day = 1;
this.month=1;
this.year +=1;
}
if(this.day==30){
this.day = 1;
this.month +=1;
}
}
public void advance(int howManyDays){
if(howManyDays < 30){
if(this.day<30 && (this.day + howManyDays < 30)){
this.day += howManyDays;
}
if(this.day==30 && this.month==12){
this.day = howManyDays;
advance();
}
if(this.day==30){
this.day = howManyDays;
this.month +=1;
}
}
if(howManyDays== 30 && this.month==12){
this.day = howManyDays;
advance();
}
if(howManyDays == 30){
this.month += 1;
}
}
public SimpleDate afterNumberOfDays(int days){
SimpleDate obj = new SimpleDate(days, this.month,this.year);
return obj;
}
}
但是当我用:
SimpleDate date = new SimpleDate(30, 12, 2011); date.advance(3);
现在日期应为2012年3月3日。应为:
[3.1.2012]
,但为:[4.12.2011]
我的任务是:实现将日期移动一天的public void advance()方法。在本练习中,我们假设每个月都有30天。注意!在某些情况下,您需要更改值...
之所以会这样,是因为您设置了日期,然后调用了advance()
。因此,将日期更改为3
,但现在您用日期advance
调用了3.12.2011
,这将按原样生成4.12.2011
。
我建议仅使用while
循环而不是多个嵌套的if
语句来简化您的方法...
在您的测试用例中,您通过了此块: