分析:大家都知道,每年的總共日期,要么就是365天,要么就是366天,具體是取決於閏年還是平年,更確切的說就是每年二月是28天還是29天,歸結到這個問題,有一個關鍵的認識點,就是求解這一年是閏年(366天)還是平年(365天)。
平年還是閏年計算算法:
1. 年份能被4整除,但不能被100整除;
2. 能被400整除
下面給出具體算法:
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 題目:輸入某年某月某日,判斷這一天是這一年的第幾天?
*/
public class NaYiTian {
public static void main(String[] args){
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
try {
//錄入鍵盤的數據
String str=bf.readLine();
//分割年月日
String[] strArr=str.split("-");
int year=Integer.parseInt(strArr[0]);
int month=Integer.parseInt(strArr[1]);
int towMonth=28;
//判斷平年還是閏年
if((year%4==0&&year%100!=0)||(year%400==0)){
towMonth=29;//閏年多一天
}
int totalDay=0;
int[] months={31,towMonth,31,30,31,30,31,31,30,31,30,31};
//前幾個月加上本月的天數
for(int i=0;i<months.length;i++){
if(month>=i+1){
if(month==i+1){
totalDay+=Integer.parseInt(strArr[2]);
break;
}else{
totalDay+=months[i];
}
}
}
//輸出結果
System.out.println(totalDay);
} catch (IOException e) {
e.printStackTrace();
}
}
}
來自微信公眾號:編程社

程序員日常進階寶典,歡迎關注!
