This question already has answers here:
Java Code for calculating Leap Year

(20 个回答)


3年前关闭。




这是我所拥有的:
Scanner input = new Scanner(System.in);
    System.out.print("Enter a year: ");
    int Year = input.nextInt();
    System.out.print("Enter a month (first three letters with the first"
            + " letter uppercase): ");
    String Month = input.next();

    String ThirtyOne = "Jan" + "Mar" + "May" + "Jul" + "Aug" + "Oct" + "Dec";
    String DaysThirtyOne = ThirtyOne.substring(21) + "31";

    String Thirty = "Apr" + "Jun" + "Sep" + "Nov";
    String DaysThirty = Thirty.substring(12) + "30";

    String TwentyEight = "Feb";
    String DaysTwentyEight = TwentyEight.substring(3) + "28";
    String DaysLeapYear = TwentyEight.substring(3) + "29";


    boolean isLeapYear = ((Year % 4 == 0) && (Year % 100 != 0) && (Year % 400 == 0));

    if (ThirtyOne.contains(Month)) {
        System.out.println(Month + " " + Year + " has " + DaysThirtyOne
                + " days in it.");
    }
    if (Thirty.contains(Month)) {
        System.out.println(Month + " " + Year + " has " + DaysThirty
                + " days in it.");
    }
    if(TwentyEight.contains(Month)) {
        System.out.println(Month + " " + Year + " has " + DaysTwentyEight
                + " days in it.");
    }
    if (isLeapYear) {
        System.out.println(Month + " " + Year + " has " + DaysLeapYear
                + " days in it.");
    }

我是编程新手,所以如果这段代码看起来不成熟,我不会感到惊讶。无论如何,我让用户输入了一年和一个月(前三个字母)。我为闰年创建了一个 boolean 变量,表示用户输入的任何年份都需要被 4、100 和 400 整除。用户输入)中包含 DaysLeapYear。”我想我的算法有问题,因为如果我取出TwentyEight的if语句并只保留闰年if语句,计算机甚至不会打印出如果是闰年二月会有多少天.再说一次,我认为我在算法中出错了,但它可能在其他地方,我希望再看看这个,看看是否有人看到了我没有看到的东西,因为我毕竟是新手。

最佳答案

首先你的 isLeapYear 条件需要改变。

boolean isLeapYear = ((Year % 4 == 0) && (Year % 100 != 0) || (Year % 400 == 0));

接下来您的 if(TwentyEight.contains(Month)) 为此需要更改以考虑闰年。
if(TwentyEight.contains(Month) && !isLeapYear) {
        System.out.println(Month + " " + Year + " has " + DaysTwentyEight
                + " days in it.");
}

10-08 13:34