“三天打鱼,两天晒网”问题求解
问题描述: 中国有句俗语叫“三天打鱼两天晒网”。某人从2010年1月1日起开始“三天打鱼两天晒网”,问这个人在以后的某一天中是“打鱼”还是“晒网”。
求解思路
计算某一天是在打鱼还是晒网,关键在于计算这一天距离初始时间2010.1.1 的天数差days。days%5等于1、2、3时,说明这一天在打鱼,否则就在晒网。而不同的年份不同的月份天数都不尽相同,闰年的二月有29天,平年只有28天,而1,3,5,7,8,10,12月有31天,3,6,11月有30天,所以需要区别计算某年某月的具体时间。
程序流程图
具体代码
package Time;
import java.lang.reflect.Array;
import java.util.Scanner;
public class date {
// 建立俩个月份的数组,分别对应闰年和平年
private int[] DayOfMonth = {0,31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
private int[] dayOfMonth = {0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 判断是否为闰年
public boolean isLeap (int year) {
if (year % 4 == 0 && year % 100 != 0) {
return true;
} else if (year % 400 == 0) {
return true;
} else {
return false;
}
}
// 通过一个计算全年天数的函数优先计算这一年的天数
public int daysofyear (int year){
if (isLeap(year)){
return 366;
}
else return 365;
}
// 获取当月天数
public int getdays(int year,int month){
if (isLeap(year)){
return DayOfMonth[month];
}
else {
return dayOfMonth[month];
}
}
boolean isreal(){
return false;
}
public static void main (String[] args) {
date A=new date();
Boolean P=true;
int days=0;
int origin=2010;
Scanner scanner=new Scanner(System.in);
System.out.println("请输入年份");
int x = scanner.nextInt();
System.out.println("请输入月份");
int y=scanner.nextInt();
System.out.println("请输入几号");
int z=scanner.nextInt();
for (;x<origin;x++){
days+=A.daysofyear(x);
}
for (int i=1;i<y;i++){
days+= A.getdays(x,i);
}
// 对该月的天数做判断,如果输入的天数超过实际,报错。
if (z>A.dayOfMonth[y]){
System.out.println("错误,该月没有这么多天!!");
P= A.isreal();
}
else days+=z;
if (P){
if (days % 5 == 0 || days % 5 == 4) {
System.out.println("这天在晒网!");
} else System.out.println("这天在打鱼!");
}
}
}
代码调试运行结果