今天正式成立了Insane Code奖,用于鼓励、激发、奖励那些写出Insane Code的Programmer。
关于Homework2,Method太多,Method从上往下依次讨论。
1、最普通的Constructor没啥好说的,记得validate就行。
2、String型的Contructor,我用了String.split by “/”的方法,也可以复杂点用substring等方法。Split by Slash将结果以Array形式返回,然后读取并Parse即可。
public Date(String s) {
String fractions[] = new String[3];
fractions = s.split("/");
if (Date.isValidDate(Integer.parseInt(fractions[0]), Integer.parseInt(fractions[1]), Integer.parseInt(fractions[2]))) {
this.month = Integer.parseInt(fractions[0]);
this.day = Integer.parseInt(fractions[1]);
this.year = Integer.parseInt(fractions[2]);
}
else {
System.out.println("The date is invalid baby!");
System.exit(0);
}
}
3、LeapYear不用说。
4、daysInMonth我用的Switch方法,很直观方便。
5、下一个validate date的method,就把所有false都挑出来,剩下的即是true。
6、ToString不用说。
7、isBefore同validate的思路,即把所有true都挑出来,剩下即是false。
public boolean isBefore(Date d) {
if (this.year < d.year) {
return true;
} else if ((this.year == d.year) && (this.month < d.month)) {
return true;
} else if ((this.year == d.year) && (this.month == d.month) && (this.day < d.day)) {
return true;
} else {
return false;
}
}
8、isAfter这里,可以用Insane Code!A日期 isAfter B日期即是B日期 isBefore A日期。不用考虑A==B的情况,因为,两者都是false。所以直接一行搞定。
Feat. Albert Su, Albert成为首届Insane Code获得者。
return d.isBefore(this);
这个Method也有其他写法,比如 !isBefore 但要考虑相等情况。
9、dayInYear即用for循环即可,考虑leap year的情况。
int count = 0;
for (int i = 1; i < this.month; i++) {
count = Date.daysInMonth(i, this.year) + count;
}
count = count + this.day;
return count;
10、Difference有两种思路:一、用数学方法,对两个日期相减,考虑闰年情况,并合理调用dayInYear这个方法。这也是大多数人都会用的方法。用个for循环,把year都加在一起,在减掉前面加上后面即可。如2000.04.01 --- 2002. 07.03,即:2000 + 2001 - 0401.dayInYear + 0703.dayInYear.
int theYear = 0;
int count = 0;
if (this.isAfter(d)) {
for (int i = d.year; i < this.year; i++) {
if (Date.isLeapYear(i)) {
theYear = 366;
} else {
theYear = 365;
}
count = theYear + count;
}
count = count - d.dayInYear() + this.dayInYear();
return count;
} else {
for (int i = this.year; i < d.year; i++) {
if (Date.isLeapYear(i)) {
theYear = 366;
} else {
theYear = 365;
}
count = theYear + count;
}
count = count - this.dayInYear() + d.dayInYear();
return (-count);
}
下一个方法是思想很简单的一个让计算机强搞的方法。即:让落后的那个日期,过一天,记个数,过一天,记个数,直到它追上后面那个,然后返回记得数即可。但需要加一个额外的private方法,我取名叫:liveALife。
private void liveALife() {
if (this.day < Date.daysInMonth(this.month, this.year)) {
this.day++;
} else {
this.day = 1;
if (this.month < 12) {
this.month++;
} else {
this.month = 1;
this.year++;
}
}
}