日期计算器:告诉某个日期是星期几

我正在尝试用 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;

        }


呼啦一阵风
浏览 148回答 2
2回答

繁花如伊

问题在于找到闰年的数量。您的逻辑也在计算 2000 年。1999-12-31 和 2000-01-01 的闰年数应该相同。只有当月份大于二月时,您才需要考虑 2000 年。仅当输入日期大于 2 月 28 日时才增加 sumLeapDaysInLeapYears

米脂

与其要求我们调试您的整个代码,不如考虑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());输出:星期五周六
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java