我正在嘗試用 Java 編寫一個程序(這是一項學校作業,它告訴你某個日期是星期幾。(日期應該寫在 yyyy-mm-dd 的表格上。)我以為我來了使用以下代碼的解決方案,但后來我發現了一個錯誤。當您運行代碼并在對話框中輸入 1999-12-31 時,程序會告訴您輸入的日期 (1999-12-31) 是星期五。但是當您輸入日期 2000-01-01(即 1999-12-31 之后的一天)時,程序會告訴您這一天是星期日!星期六怎么了?當您輸入 2000-02-29 和 2000-03-01 時,也會出現類似的問題,它們都給出了周三的答案!我還沒有注意到,僅當您輸入 2000-01-01 和 2000-02-29 之間的日期時才會出現此錯誤。如果有人能幫我找出錯誤的原因并解決問題,我將不勝感激!import static javax.swing.JOptionPane.*;import static java.lang.Math.*;public class DateCalc { // Here, between the DateCalc class declaration and the main method, several methods used in the program are // constructed. // The method isLeapYear tests whether the entered year is a leap year or not. private static boolean isALeapYear(int year) { // If the year is a multiple of 4 and not a multiple of 100, or a multiple of 400, then it is a leap year. if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { return true; } else { return false; } } // A method that tests whether a given string is written as a valid date. private static boolean isAValidDate(int year, int month, int day) { int maxValidYear = 9999; int minValidYear = 1754; if (year > maxValidYear || year < minValidYear) { return false; } if (month < 1 || month > 12) { return false; } if (day < 1 || day > 31) { return false; }
2 回答

繁花如伊
TA貢獻2012條經驗 獲得超12個贊
問題在于找到閏年的數量。您的邏輯也在計算 2000 年。1999-12-31 和 2000-01-01 的閏年數應該相同。只有當月份大于二月時,您才需要考慮 2000 年。僅當輸入日期大于 2 月 28 日時才增加 sumLeapDaysInLeapYears

米脂
TA貢獻1836條經驗 獲得超3個贊
與其要求我們調試您的整個代碼,不如考慮LocalDate獲得所需的結果:
LocalDate ldt = LocalDate.parse("1999-12-31");
System.out.println(ldt.getDayOfWeek());
LocalDate ldt2 = LocalDate.parse("2000-01-01");
System.out.println(ldt2.getDayOfWeek());
輸出:
星期五
周六
添加回答
舉報
0/150
提交
取消