分析:大家都知道,每年的总共日期,要么就是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();
}
}
}
来自微信公众号:编程社
程序员日常进阶宝典,欢迎关注!
来源:oschina
链接:https://my.oschina.net/u/4286839/blog/3407898