java - 为什么我的闰年算法不起作用(Java)?

标签 java algorithm leap-year

<分区>

这是我的:

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 整除。然后,我创建了一个 if 语句来判断是否是闰年以打印出“Feb(无论是哪一年)用户输入)中有 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.");
}

关于java - 为什么我的闰年算法不起作用(Java)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26149028/

相关文章:

algorithm - Dijkstra 算法在排序列表/数组实现的优先级队列上的运行时间

string - 以下用于查找不同字符串的算法是否有效?

Javascript:计算给定年份的月份天数

java - 如何使用链接源引用获取工作项 ID?

java - c :set tag to set a non-primitive type value

Java内存: Object consumes thrice the size it should

c - 如何在C中以编程方式查找leap年

JavaFX DatePicker 返回 null

algorithm - 为什么在广度优先搜索中需要访问状态?

php - 闰年和非闰年分表