Java-关于计算今天是今年的第多少天

在尚硅谷学习的第6天,作业有个这个,我查了一下大部分都是用 switch 的好像没我这种的

自己琢磨半天,来这边找点成就感波~

基本思路就是:

确认年份(year)区分平年闰年;

确认月份(month)把当月之前的月份天数加上;

确认天数(day)把当月的天数加上;

因此需要定义一个变量days来存储计算结果并打印。

变量year用来判断平年闰年,变量month用来确定遍历多少次,变量day提前赋给days用作叠加。

代码如下:

public class demo5 {
    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();

        //闰年1-12月天数: 31,29,31,30,31,30,31,31,30,31,30,31
        //平年1-12月天数: 31,28,31,30,31,30,31,31,30,31,30,31

        int days = day;
        int[] monthArr = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  //闰年
        int[] monthBrr = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  //平年

        //如果是闰年
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            for (int i = 1; i < month; i++) {
                days += monthArr[i];
            }
        } else { //如果是平年
            for (int i = 1; i < month; i++) {
                days += monthBrr[i];
            }
        }
        System.out.println("今天是"+year + "年的第:"  + days + "天");

    }

}
 

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值