爪哇岛:二十世纪的第一个月(1901年1月1日至2000年12月31日)有多少个星期日下降?
发布时间:2020-05-24 22:33:18 所属栏目:Java 来源:互联网
导读:我是编程和 java的新手,我正在尝试解决以下问题: 在二十世纪的第一个月(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 +
|
我是编程和
java的新手,我正在尝试解决以下问题:
这是我的代码: 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);
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
