计算天数

这里写自定义目录标题


计算天数:
输入年月日,计算该填是本年的第几天。例如1990 年9 月20 日是1990 年的第263 天,2000 年5 月1 日是2000 年第122 天。

 import java.util.Scanner;


public static void main(String[] args) {

    int num[] = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//定义数组,数组包含每个月的日期
    System.out.println("请输入年份:");
    Scanner a = new Scanner(System.in);
    int year = a.nextInt();     //输入年份
    System.out.println("请输入月份:");
    Scanner b = new Scanner(System.in);
    int month = b.nextInt();            //输入月份
    System.out.println("请输入日期:");
    Scanner c = new Scanner(System.in);
    int day = c.nextInt();        //输入日期

    if (year % 4 == 0 && year % 100 != 0) {  //算出闰年 闰年只可以被4整除,但是不能被100整除的数为闰年
        num[1] = 29;      //如果为true则给num[1]赋值为29,也就是2月闰年为29天
    } else if (year % 400 == 0) {         //算出世纪闰年,只能被400整除,如果为true则为闰年,2月有29天
        num[1] = 29;            //如果为true则为闰年,2月有29天
    } else {
        num[1] = 28;              如果以上if都没为true则2月为28天
    }

    month--;                            //数组开始索引是0,而定义的数组天数是从一月开始算起 所以这里month(月份)要-1
    int end = 0;
    if (month <= 12) {                    //判断输入的月份是否输入规范
        for (int i = 0; i < month; i++) {     //循环索引,i直到输入的月份为止
            end = num[i] + end;              //循环加,输入的月份之前的数值
        }

        if (day <= num[month]) {            //判断输入的日期是否合理
            end += day;                  //如果为true则end加上输入的日期

            System.out.println(year + "年第" + end + "天");  //打印最终结果
        } else {
            System.out.println("输入错误的日期");  //如果日期为false则打印输出
        }

    } else {
        System.out.println("输入错误的月份");//如果月份为false则打印输出
    }
}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值