输入一个年月日,输出是指定日期是这一年的第几天--蘑菇街面经

题目要求:输入年月日,输出输入的日期,是这一年的第几天;

问题分析:分析这一年的第几天,首先,月有大小月之分,1,3,5,7,8,10,12。都是31天。而4,6,9,11则是30天,2月份的天数,取决于给定年份是平年还是闰年,平年则为28天,闰年为29天;

判断某一年是否是闰年:

能被4整除,不能被100整除;

能被100整除,也能被400整除

代码如下:

import java.util.Scanner;

public class CountDays {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()){
			System.out.println(countDays(sc.nextLine()));
		}
	}
	public static int countDays(String date){
		if(date == null || date.length() == 0){
			return -1;
		}
		String[] dates = date.split(" ");
		if(dates.length != 3){
			return -1;
		}
		int year = Integer.parseInt(dates[0]);
		int month = Integer.parseInt(dates[1]);
		int day = Integer.parseInt(dates[2]);
		int sumDay = 0;
		int dayOfMonth = 0;
		for(int i=1; i < month; i++){
			switch(i){
				case 1:
				case 3:
				case 5:
				case 7:
				case 8:
				case 10:
				case 12:{
					dayOfMonth = 31;
					break;
				}
				case 4:
				case 6:
				case 9:
				case 11:{
					dayOfMonth = 30;
				}
				case 2:{
					if((year % 100 != 0 && year % 4 == 0) || 
							(year % 100 == 0 && year % 400 == 0)){
						dayOfMonth = 29;
					}
					else{
						dayOfMonth = 28;
					}
					break;
				}
				default: break;
					
					
					
			}
			sumDay+=dayOfMonth;
		}
		return sumDay+day;
		
	}
}
点赞