中国有句俗语叫“三天打鱼两天晒网”。某人从2010年1月1日起开始“三天打鱼两天晒网”,问这个人在以后的某一天中是“打鱼”还是“晒网”。用C或C++语言/java/python实现程序解决问题。
基本要求:1.程序风格良好(使用自定义注释模板),提供友好的输入输出。
提高要求:1.输入数据的正确性验证。
2.使用文件进行数据测试。如将日期 20100101 20111214 等数据保存在in.txt文件中,程序读入in.dat文件进行判定,并将结果输出至out.txt文件。
源代码(java):
package 作业1;
import java.util.Scanner;
public class FishingAndDrying {
public static void main(String[] args) {
boolean a = true;//变量a用于判断退出
//可多次判断日期
while(a){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年份:");
int year = scanner.nextInt();
//判断输入年份是否合法
while(year<2009)
{
System.out.println("您输入的年份太早啦!");
System.out.println("请再次输入年份:");
year = scanner.nextInt();
}
System.out.println("请输入月份:");
int month = scanner.nextInt();
//判断输入的月份是否合法
while( month < 1 | month > 12)
{
System.out.println("没有这个月吧!");
System.out.println("请再次输入月份:");
month = scanner.nextInt();
}
System.out.println("请输入日期");
int day = scanner.nextInt();
int day0 = getDays(year, month);//输入的月有多少天
//判断输入的日期是否合法
while(day > day0 | day < 1 )
{
System.out.println("这个月有这天吗?");
System.out.println("请再次输入日期:");
day = scanner.nextInt();
}
judge(getAllDays(year, month, day));
//判断是否退出
System.out.println("是否退出?Y/N");
String b = scanner.next();
char c = b.charAt(0);
if(c == 'Y')
{
a = false ;
}
}
}
// 判断打鱼还是晒网
public static void judge(int days) {
int x = days % 5;
if (x >= 1 && x <= 3) {
System.out.println("Fishing!");
} else if (x == 4 || x == 0) {
System.out.println("Drying!");
}
}
// 判断是否是闰年
public static boolean runNian(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return true;
}
return false;
}
// 计算距离输入日期多少天
public static int getAllDays(int year, int month, int day) {
int sum = 0;
// 计算2010-(year-1)之间有多少天
for (int i = 2010; i < year; i++) {
if (runNian(i)) {
sum += 366;//闰年366天
} else {
sum += 365;//平年365天
}
}
// 计算本年内该日期之前共有多少天
sum += getCurrentDays(year, month, day);
return sum;
}
// 判断每月有几天
public static int getDays(int year, int month) {
int days = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
if (runNian(year)) {
days = 29;
} else {
days = 28;
}
break;
}
return days;
}
// 计算本年内该日期之前共有多少天
public static int getCurrentDays(int year, int month, int day) {
int sum = 0;
for (int i = 1; i < month; i++) {
sum += getDays(year, i);// 判断每月有几天
}
return sum + day;
}
}
流程图:
有一个问题就是在是否退出时,输入了Y还是没有退出
原因:输入字符时出错
修改后:
System.out.println("是否退出?Y/N");
String b = scanner.next();
char c = b.charAt(0);
if(c == 'Y')
{
a = false ;
}
调试:
测试: