您已获得以下信息,但您可能更愿意自己做一些研究。
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
在二十世纪(1901 年 1 月 1 日到 2000 年 12 月 31 日)中,每个月的第一天有多少个星期日?
解决方案:
我的以下逻辑给了我 173 个星期日,而实际上有 171 个星期日!额外的 2 天是从哪里来的?
public static void main(String args[]) {
Date startDate = new Date(1901, Calendar.JANUARY, 01);
Date endDate = new Date(2000, Calendar.DECEMBER, 31);
checkSundays(startDate, endDate);
}
private static void checkSundays(Date start, Date end) {
int dayNum;
Calendar startDate = Calendar.getInstance();
startDate.setTime(start);
System.out.println(startDate.getTime());
Calendar endDate = Calendar.getInstance();
endDate.setTime(end);
System.out.println(endDate.getTime());
int count = 0;
while (startDate.before(endDate)) {
for (int i = 1; i < 13; i++) {
dayNum = startDate.get(Calendar.DAY_OF_WEEK);
if (dayNum == 1) {
count++;
}
System.out.println(startDate.getTime());
startDate.add(Calendar.MONTH, 1);
}
System.out.println("Count " + count);
}
}
最佳答案
您的以下代码使用了 Date
的弃用构造函数
Date startDate = new Date(1901, Calendar.JANUARY, 01);
System.out.println(startDate);
这是不正确的,它会打印
Thu Jan 01 00:00:00 IST 3801
所以使用Calendar
构造Date
,
Calendar startDateCal = createDateInstance(0,1901,1)
Calendar endDateCal = createDateInstance(11,2000,13)
和一个工厂方法
public static Date createDateInstance(int month, int year, int date){
Calendar cal= Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DATE, date);
return cal.getTime();
}
关于java - Java 中的欧拉计划 #19,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11292220/