Java循环:闰年

概念

闰年是指公历年份中除以4余数为0,且除以100余数不为0,或者除以400余数为0的年份。闰年通常有366天,比平年多1天。

计算一个年份是否为闰年,可以使用以下公式:

  1. 如果该年份能够被4整除但不能被100整除,或者能够被400整除,那么该年份就是闰年。

  2. 否则,该年份就是平年。

题型

1.统计范围内闰年的个数

public static void main(String[] args) {
        //找出2000--2500里闰年的个数 ?
        int count = 0;
        for(int year = 2000;year <= 2500;year++){
            if (year%4==0&&year%100!=0||year%400==0){
                System.out.println(year+"是闰年");
                count++;
            }
        }
        System.out.println("共有"+count+"个闰年");
    }

2.switch判断一年中的第几天

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个年份:");
        int year = sc.nextInt();
        System.out.println("请输入一个月份:");
        int month = sc.nextInt();
        System.out.println("请输入一个日期:");
        int day = sc.nextInt();

        for (int i = 1;i<month;i++){
            switch (month){
                case 1: case 3: case 5: case 7: case 8: case 10: case 12:
                    day+=31;
                    break;
                case 4: case 6: case 9: case 11:
                    day+=30;
                    break;
                case 2:
                    if(year%4==0&&year%100!=0||year%400==0){
                        day+=29;
                    }else {
                        day+=28;
                    }
                    break;
            }
        }
        System.out.println("这是"+year+"年的第"+day+"天");
    }

3.数组实现判断一年中的第几天

public static void main(String[] args) {
        //请输入一个,年,月,日,判断是这一年的第多少天(注意闰年)
        Scanner input = new Scanner(System.in);
        System.out.println("请输入年:");
        int year = input.nextInt();
        System.out.println("请输入月:");
        int month = input.nextInt();
        System.out.println("请输入日:");
        int day = input.nextInt();

        int days = 0;
        // 判断是否是闰年
        boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
        // 计算每个月的天数
        int[] monthDays = {31, isLeapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        // 计算总天数
        for (int i = 0; i < month - 1; i++) {
            days += monthDays[i];
        }
        days += day;
        System.out.println(year + "年" + month + "月" + day + "日是该年的第 " + days + " 天");
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值