我正在做的项目包括:'编写一个程序,提示输入日期(月、日、年)并报告该日期是星期几。有可能 知道 1601 年 1 月 1 日是星期一很有帮助。这是“Building Java Programs - A Back to Basics Approach, 2nd Edition”的练习,这本书是我买来自学 Java 的。非常感谢任何反馈,但我确实要求你解释为什么你会以另一种/某种方式做某事。谢谢!
所以,我的问题是,虽然对于接近 1600 年的日期,它给出了正确的日期(我相信),但最近几天情况并非如此,它们有三天的偏移量(至少我的那些检查)。为什么会发生这种情况,我该如何解决?谢谢!
我的代码:
// finds the day of the week of the given date
public static String dayFinder(int month, int day, int year) {
// handle invalid input
if (month > 12 || month < 1 || day > 31 || day < 1) {
throw new IllegalArgumentException("Month must be between "
+ "1 and 12 and Day must be between 1 and 31.");
}
// convert to "absolute" day, covering day and month
int absoluteDay = monthToDay(month, day, year);
// convert year to days and add to "absolute" day
absoluteDay += yearToDay(year);
if (absoluteDay % 7 == 1) {
return "Monday";
} else if (absoluteDay % 7 == 2) {
return "Tuesday";
} else if (absoluteDay % 7 == 3) {
return "Wednesday";
} else if (absoluteDay % 7 == 4) {
return "Thursday";
} else if (absoluteDay % 7 == 5) {
return "Friday";
} else if (absoluteDay % 7 == 6) {
return "Saturday";
} else { // absoluteDay % 7 == 0
return "Sunday";
}
}
// calculates the number of days present in a given
// date since the beginning of the year
public static int monthToDay(int month, int day, int year) {
// convert to "absolute" day
int absoluteDay = 0, daysTo31 = 0;
// iterate through months
for (int i = 0, loopMonth = month; i < month; i++) {
if (loopMonth == 1 || loopMonth == 3 || loopMonth == 5
|| loopMonth == 7 || loopMonth == 8 || loopMonth == 10
|| loopMonth == 12) {
absoluteDay += 31;
daysTo31 = 0;
} else if (loopMonth == 2) {
if (year % 4 != 0) {
absoluteDay += 28;
daysTo31 = 3;
} else { // leap year
absoluteDay += 29;
daysTo31 = 2;
}
} else { // month = 4, 6, 9 or 10
absoluteDay += 30;
daysTo31 = 1;
}
loopMonth--;
}
// adjust to specific day
absoluteDay -= (31 - day - daysTo31);
return absoluteDay;
}
// calculates the number of days between
// (the beginning of) the given year and
// (the beginning of) the reference year 1601
public static int yearToDay(int year) {
// convert to "absolute" day
int absoluteDay = 0;
year -= 1601;
// iterate through years
for (int i = 0, loopYear = year; i < year; i++) {
if (loopYear % 4 != 0) {
absoluteDay += 365;
} else { // leap year
absoluteDay += 366;
}
loopYear--;
}
return absoluteDay;
}
//1604 年 (MDCIV) 是星期四开始的闰年
最佳答案
您的问题可能与闰年有关。
由于维基百科:
除了能被 100 整除的年份外,所有能被 4 整除的年份都是闰年;能被 400 整除的世纪年仍然是闰年。例如,1900 年不是闰年; 2000 年是闰年。
[link]
这就是为什么你有太多三天(1700、1800、1900)的原因。
关于java - Java 中的工作日查找器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20340648/