求出该年的第几天

来源:互联网 发布:如何优化企业资本结构 编辑:程序博客网 时间:2024/05/16 11:06

问题描述: 给出年月日,求出是该年的第几天。
思路:使用数组分别存储十二个月对应的天数,由于平年的二月是28天,闰年的二月是29天,默认二月为28天,最后判断是否为闰年,是则加上1天,否则不加。

import java.util.Scanner;/** * 求出该年的第几天 */public class Main {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        int[] arr = {31,28,31,30,31,30,31,31,30,31,30,31};        int days = 0;        while (in.hasNext()){            //输入年月日            int year = in.nextInt();            int month = in.nextInt();            int day = in.nextInt();            //累加1月到(输入月份-1)月份的天数            for (int i = 0; i < month-1; i++){                days += arr[i];            }            //加上该月的天数            days += day;            //如果是闰年并且大于2月,则天数加1            if((year % 4 == 0) && (year % 100 != 0) || year % 400 == 0){                if (month > 2){                    days += 1;                }            }            System.out.println(days);        }    }}
原创粉丝点击