以下是用Java语言编写的判断月份天数的程序代码:

import java.util.Scanner;

public class MonthDays {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print('请输入年份:');
        int year = scanner.nextInt();
        System.out.print('请输入月份:');
        int month = scanner.nextInt();

        int days = 0;
        boolean isValidMonth = true;

        if (month < 1 || month > 12) {
            isValidMonth = false;
        } else if (month == 2) {
            if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
                days = 29;
            } else {
                days = 28;
            }
        } else if (month == 4 || month == 6 || month == 9 || month == 11) {
            days = 30;
        } else {
            days = 31;
        }

        if (isValidMonth) {
            System.out.println(year + '年' + month + '月份的天数是' + days + '天。');
        } else {
            System.out.println('月份输入不正确。');
        }
    }
}

这段代码首先通过Scanner类获取用户输入的年份和月份,并用if语句判断月份是否在有效范围内。如果月份不在1-12之间,则将isValidMonth变量设为false,表示月份输入不正确。如果月份为2月,则根据年份判断是否为闰年,分别将days变量设为29或28。如果月份为4、6、9、11月,则将days变量设为30。对于其他月份,则将days变量设为31。最后根据isValidMonth的值输出判断结果。

Java程序:根据年份和月份计算天数 - 闰年判断

原文地址: https://www.cveoy.top/t/topic/paCn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录