Java 计算月份天数

最简单的方法

import java.time.LocalDate;
import java.util.Calendar;
import java.util.Scanner;
//声明LocalDate和Calendar和Scanner
public class yue {
//yue是我的文件名。
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入年 :");
       int year = sc.nextInt();
       //int定义year,=号赋值(用户输入的值)
        System.out.println();
        System.out.print("请输入月 :");
       int month = sc.nextInt();
       //定义month,=号赋值(用户输入的值)
        var c = Calendar.getInstance();
        int days = 0;
        switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
        days = 31;
        break;
        //定义31天的月份。
        case 4:
        case 6:
        case 9:
        case 11:
        days = 30;
        break;
        //定义30天的月份。
        case 2:
        days = year % 400 == 0 || year % 4 == 0 && year % 100 != 0 ? 29 : 28;
        ***//此行命令为计算闰年的公式!!!***
        LocalDate now = LocalDate.of(year, month, 1);
        days = now.isLeapYear() ? 29 : 28;
        break;
        //定义2月的天数
        default:
        days = 0;
        break;
        }
        System.out.printf("%d年%d月有%d天", year, month, days);
    }
}

方法二(Switch)

public class Switch01 {
//Switch01为我的文件名!!!
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
       System.out.print("请输入年 :");
        int y = sc.nextInt();
        //定义y并赋值
        System.out.println();
        System.out.print("请输入月 :");
        int m = sc.nextInt();
        //定义m并赋值
        int days = switch (m){
            case 2 -> y % 400 == 0 || y % 4 == 0 && y % 100 != 0 ? 29 : 28;
            ***//闰年计算公式***
            case 4,6,9,11 -> 30;
            //定义30天的月份
            default -> 31;
            //除30天的月份和2月份之外的月份为31天。
        };
        System.out.printf("%d年%d月有%d天",y,m,days);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值