PS:这题与之前的一篇《求一个日期是星期几》方法类似,可做参考
老师说:“每日一题,必将成功。” 而小明遵从“三天打鱼两天晒网”的古训。小兰来找小明出去玩,
小明说,那要看看今天我是打鱼还是晒网。勤奋的你帮小明算算吧?
输入格式:
输入多行,每行一个日期,第一行的日期是小明开始“三天打鱼两天晒网”的日子,接下来每一行日期是小兰来找小明出去玩的日子。日期格式如“2024-2-18”。
输出格式:
对每一个小兰找小明出去玩的日子,输出一行“Fishing”或“Drying”,分别代表小明今天打鱼或晒网。
输入样例:
2024-2-16
2024-2-18
2024-3-20
输出样例:
Fishing
Drying
import java.util.Scanner;
public class Main{
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
String strFirst;//开始日期字符串
String strToday;//计算日期字符串
int interDays = 0;//相隔的天数
strFirst = sc.next();
while(sc.hasNext()){
strToday = sc.next();
interDays = betweenDays(strFirst,strToday);
if(interDays % 5 <= 2){
System.out.println("Fishing");
}else{
System.out.println("Drying");
}
}
}
//计算两个日期间相隔的天数
private static int betweenDays(String begin,String end){
int beginYear = 0,beginMonth = 0,beginDay = 0;//开始日期的年月日
int endYear = 0,endMonth = 0,endDay = 0;//当前日期的年月日
int beginDays = 0;//从0年1月1日到开始日期的天数
int endDays = 0;//从0年1月1日到当前日期的天数
String[] beginStr = begin.split("-");
String[] endStr = end.split("-");
beginYear = Integer.parseInt(beginStr[0]);
beginMonth = Integer.parseInt(beginStr[1]);
beginDay = Integer.parseInt(beginStr[2]);
endYear = Integer.parseInt(endStr[0]);
endMonth = Integer.parseInt(endStr[1]);
endDay = Integer.parseInt(endStr[2]);
beginDays = count(beginYear,beginMonth,beginDay);
endDays = count(endYear,endMonth,endDay);
return endDays - beginDays;
}
//求从0年1月1日到当前日期的天数
private static int count(int year,int month,int day){
int countDays = 0;
for(int i = 0;i < year;i++){
if(isLeap(i))
countDays += 366;
else
countDays += 365;
}
for(int i=1;i<=month-1;i++){
switch(i){
case 1: case 3 : case 5: case 7: case 8: case 10: case 12: countDays+=31; break;
case 2:countDays+= isLeap(year)?29:28;
case 4: case 6 : case 9: case 11: countDays+=30; break;
}
}
countDays += day;
return countDays;
}
//判断是否是闰年
private static boolean isLeap(int year){ if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){
return true;
}
return false;
}
}