我是编程和
java的新手,我正在尝试解决以下问题:
在二十世纪的第一个月(1901年1月1日至2000年12月31日),有多少个星期日下降?
在二十世纪的第一个月(1901年1月1日至2000年12月31日),有多少个星期日下降?
这是我的代码:
int count,sum = 0; for (int i = 1901; i < 2001; i++) { LocalDate test = LocalDate.of(i,1,1); sum += test.lengthOfYear(); } for (int i = 1; i < sum; i++) { LocalDate date1 = LocalDate.of(1901,1); date1 = date1.plusDays(i); if (date1.getMonth() == JANUARY && date1.getDayOfWeek() == SUNDAY) { count++; } } System.out.println(count);
如果我打印结果,它似乎工作正常.
我的结果是443,但正确的答案是171.我做错了什么?
谢谢!
解决方法
我看到一些错误:
public static void main(String[] args) { int count,sum = 0; for (int i = 1901; i < 2001; i++) { // There is a mistake here,I dont know what you want to compute in this loop! LocalDate test = LocalDate.of(i,1); sum += test.lengthOfYear(); } for (int i = 1; i < sum; i++) { LocalDate date1 = LocalDate.of(1901,1); // There is a mistake here,date1 must be outside of this loop date1 = date1.plusDays(i); // There is a mistake here,plusDays why?? if(date1.getMonth() == JANUARY && date1.getDayOfWeek() == SUNDAY) { // There is a mistake here,why are you cheking this: date1.getMonth() == JANUARY ? count++; } } System.out.println(count); }
简单的解决方案:
public static void main(String[] args) { int count = 0; LocalDate date1 = LocalDate.of(1901,Month.JANUARY,1); LocalDate endDate = LocalDate.of(2001,1); while (date1.isBefore(endDate)) { date1 = date1.plusMonths(1); if (date1.getDayOfWeek() == DayOfWeek.SUNDAY) { count++; } } System.out.println(count); }