java練習:5. 輸入年月日計算該天是這年的第幾天

例:

輸入2019 10 11

得出是 2019年10月11日是2019年的第284天

import java.util.Scanner;

public class YearMonthDay {
	
	public static void main(String[] args) {
		//輸入年月日
		Scanner sc = new Scanner(System.in);
		System.out.println("請輸入年月日");
		int year = sc.nextInt();
		int month = sc.nextInt();
		int day = sc.nextInt();
		
		//計算日期是這年的第幾天
		int sumdays = getSumDay(year, month, day);
		
		//打印該日期對應這一年是第幾天
		System.out.println(year + "年" + month + "月" + day + "日,是" + year + "年的第" + sumdays + "天");
	}
	//計算日期是這年的第幾天,例 2019 10 11
	private static int getSumDay(int year, int month, int day) {
		int dayss = 0;//保存這個日期對應這一年的總天數
		//將[1,month)之間的整月進行累加,即把1-9月整月的天數進行累加
		for(int m = 1; m < month;m++) {
			dayss += getMonthDay(year, m);
		}
		dayss += day;
		return dayss;
	}
	private static int getMonthDay(int year, int month) {
		switch (month) {
		case 1 :
		case 3 :
		case 5 :
		case 7 :
		case 8 :
		case 10 :
		case 12 :
			return 31;
		case 4 :
		case 6 :
		case 9 :
		case 11 :
			return 30;
		case 2 :
			//判斷是否是閏年,閏年29天,不是閏年28天
			if(leapYear(year)) {
				return 29;
			}else {
				return 28;	
			}
		}
		return 0;
	}
	//判斷是否是閏年
	private static boolean leapYear(int year) {
		if(year % 4 == 0 && year % 100 != 0 || year % 400 ==0) {
			return true;
		}else{
			return false;
		}
	}
	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章