计数星期日出现在每个月的第一天

时间:2014-02-27 17:14:59

标签: java date

我上面写了这段代码,以便在每个月的第一天出现星期日。我没有得到正确的结果,也不知道为什么?有什么建议吗?

import java.util.Calendar;

    public class Test{
          public static void main(String args[]) {
            int counter = 0;
            Calendar c = Calendar.getInstance();

            for (int i = 1900; i<=2000; i++){
                for (int j = 0; j <=11; j++){
                    c.set(i, j, 1);
                    int day_of_week = c.get(Calendar.DAY_OF_WEEK);
                    if(day_of_week==1){
                        counter++;
                    }
                }
            }
            System.out.println(counter);
          }   
    }

2 个答案:

答案 0 :(得分:4)

20世纪包括从1901年到2000年的几年。通过修改你的循环......

for (int i = 1901; i <= 2000; i++){

你将获得171个月。


此外,在代码中使用硬编码值通常是一件坏事;看看PearsonArtPhoto's suggestions

中的一些内容

答案 1 :(得分:3)

首先,有几件事情可以使代码更清晰。但我怀疑问题的症结在于你应该从1901年开始,因为这在技术上是本世纪的第一天。代码清理,这里有一些提示:

  1. 使用具有某些意义的变量名称,例如年份和月份。
  2. 使用常量,而不是仅枚举值(Calendar.DAY_OF_WEEK.SUNDAY
  3. 把所有东西放在一起,你就得到了:

    public class Test{
          public static void main(String args[]) {
            int counter = 0;
            Calendar c = Calendar.getInstance();
            int Day_Of_Month=1; //This makes it easier in case you want to tweak the test, to say, 
    
            for (int year = 1901; year<=2000; year++){
                for (int month = 0; month <12; month++){
                    c.set(year, month, 1);
                    int day_of_week = c.get(Calendar.DAY_OF_WEEK);
                    if(day_of_week==Calendar.DAY_OF_WEEK.SUNDAY){
                        counter++;
                    }
                }
            }
            System.out.println(counter);
          }   
    }