输入一个日期,判断该日期是该年中的第几天

业务逻辑类

package test;

public class InputDateOutputDayCount {

    //该变量统计总天数
    private int countDay = 0;

    //年
    int year;
    //月
    int month;
    //日
    int day;

    //该方法获取天数
    public int getCountDay(String date){

        //截取年月日
        String strArr[] = date.split("-");

        //转换为整型并赋值给年月日
        year = Integer.parseInt(strArr [0]);
        month =Integer.parseInt(strArr[1]);
        day = Integer.parseInt(strArr[2]);

        for (int i = 0; i < month; i++) {
            //获取天数并返回
            switch (i){
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    countDay += 31;
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    countDay += 30;
                    break;
                case 2:
                    countDay += 28;
                    break;
            }
        }
        //判断是否为闰年
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ){
            //是闰年并且月份大于2,天数就就加一天,否则不加
            if (month>2){
                countDay = countDay + day + 1;
                return countDay;
            }
            countDay +=  day;
            return countDay;

        }else {
            countDay = countDay + day;
            return countDay;
        }


    }
}

测试类

package test;

import java.util.Scanner;

public class InputDateOutputDayCountTest {

    //测试方法
    public static void main(String[] args){

        //录入函数
        Scanner scanner = new Scanner(System.in);

        //输入年份
        System.out.println("请输入年份:");
        String year = scanner.next();

        //输入月份
        System.out.println("请输入月份:");
        String mounth = scanner.next();

        //输入日
        System.out.println("请输入日:");
        String day = scanner.next();

        String date = year + "-" + mounth + "-" + day;

        //调用方法
        InputDateOutputDayCount idody = new InputDateOutputDayCount();

        //输出这一天是这一年中的第几天
        System.out.println(date + "是" + year + "年中的第" + idody.getCountDay(date) + "天。");

    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值