1. 程式人生 > >【程式14】 題目:輸入某年某月某日,判斷這一天是這一年的第幾天?

【程式14】 題目:輸入某年某月某日,判斷這一天是這一年的第幾天?

/*
	2017年3月7日10:48:42
	java基礎50道經典練習題 例14
	Athor: ZJY
	Purpose: 
	1.能被4整除而不能被100整除.(如2004年就是閏年,1800年不是.)
	2.能被400整除.(如2000年是閏年)
	【程式14】
	題目:輸入某年某月某日,判斷這一天是這一年的第幾天?
	程式分析:以3月5日為例,應該先把前兩個月的加起來,
	然後再加上5天即本年的第幾天,特殊情況,閏年且輸入
	月份大於3時需考慮多加一天。
 
*/
import java.util.Scanner;

public class ProgramNo14_1
{
	public static void main(String[] args)
	{
		System.out.print("請輸入某年某月某日,以空格區分: ");
		Scanner sc = new Scanner(System.in).useDelimiter("\\s");
		int year = sc.nextInt();
		int month = sc.nextInt();
		int day = sc.nextInt();
		sc.close();
		System.out.print("輸入的日期為:"+year+"年"+month+"月"+day+"日");
		System.out.println("該日期是一年的第"+calculateDays(year, month, day)+"天!");
	}
	private static int calculateDays(int year, int month, int day)
	{
		if((12 < month)||(0 > month)||(31 < day)||(0 > day)){
			System.out.print("輸入資料無效!!");
			System.exit(-1);
		}
	    int days = 0;
		byte[] byteArray = null;
		byte[] byteArray1 = new byte[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
		byte[] byteArray2 = new byte[]{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

		if((0 == year%400)||((0 == year%4)&&(0 != year%100))
			byteArray = byteArray2;
		else
			byteArray = byteArray1;
		
		if(byteArray[1] < day) {
			System.out.print("輸入資料無效!!");
			System.exit(-1);
		}

		for (int i=0; i<month-1; i++) {
			days += byteArray[i];
		}
		return (days + day);
	}

}
/*
	2017年3月7日10:48:42
	java基礎50道經典練習題 例14
	Athor: ZJY
	Purpose: 
	1.能被4整除而不能被100整除.(如2004年就是閏年,1800年不是.)
	2.能被400整除.(如2000年是閏年) 
*/

import java.util.Scanner;

public class ProgramNo14_2
{
	public static void main(String[] args){
		Scanner scan = new Scanner(System.in).useDelimiter("\\D");//匹配非數字
		System.out.print("請輸入當前日期(年-月-日):");
		int year = scan.nextInt();
		int month = scan.nextInt();
		int date = scan.nextInt();
		scan.close();
		System.out.println("今天是"+year+"年的第"+analysis(year,month,date)+"天");
	}
	//判斷天數
	private static int analysis(int year, int month, int date){
		int n = 0;
		int[] month_date = new int[] {0,31,28,31,30,31,30,31,31,30,31,30};
		if((year%400)==0 || ((year%4)==0)&&((year%100)!=0))
		  month_date[2] = 29;
		for(int i=0; i<month; i++)
		  n += month_date[i];
		return n+date;
	}
}