1

您将获得以下信息,但您可能更愿意自己做一些研究。

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.

在 20 世纪(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);

    }
}
4

2 回答 2

3

您的以下代码使用不推荐使用的构造函数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();

}

查看您的工作代码

于 2012-07-02T10:57:21.217 回答
0

您可以使用概率,只需一个计算器即可。

一个世纪有 100 年,每年有 12 个月的第一天。将其除以 7,您就有了答案。

它很便宜,但它有效。

于 2014-02-08T06:13:36.067 回答