一,题目:中国有句俗语叫“三天打鱼两天晒网”。某人从2010年1月1日起开始“三天打鱼两天晒网”,问这个人在以后的某一天中是“打鱼”还是“晒网”。用C或C++语言/java/python实现程序解决问题。
二.基本要求:1.程序风格良好(使用自定义注释模板),提供友好的输入输出。
提高要求:1.输入数据的正确性验证。
2.使用文件进行数据测试。如将日期 20100101 20111214 等数据保存在in.txt文件中,程序读入in.dat文件进行判定,并将结果输出至out.txt文件
三.思路:
*问题分析与算法设计
由题意将解题过程分为三步:
(1)计算从2010年1月1日至输入日期共有多少天;
(2)由于“打鱼”和“晒网”的周期为5天,所以将计算出的天数用5去除
(3)根据余数判断他是在打鱼还是晒网
四.代码
“`
package huangqianwen;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FB {
public static boolean leapYear(int year) {
// 公元年数可被4整除的为闰年,正百年数必须是可以被400整除的是闰年。
boolean bool;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
bool = true;
} else {
bool = false;
}
return bool;
}
// 计算测试年1月1日到2010年1月1日共有多少天
public static int getAllDays(int year) {
int sum = 0;
// 计算2010--(year-1)之间有多少天
for (int i = 2010; i <= year; i++) {
if (leapYear(i)) {
sum += 366;
} else {
sum += 365;
}
}
return sum;
}
// 计算测试年过了一年中的多少天
public static int getDays(int year, int month, int day) {
int days = day;
for (int i = 1; i < month; i++) {
switch (i) {
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 (leapYear(year)) {
days = 29;
} else {
days = 28;
}
break;
}
days += day;
}
return days;
}
// 判断打鱼还是晒网
public static void judge(int days) {
int x = days % 5;
if (x >= 1 && x <= 3) {
System.out.println("打鱼!");
} else{
System.out.println("晒网!");
}
}
public static void main(String[] args) throws Exception
{
List<String> list = transferFile();
String[] arr = new String[list.size()];
for(int index = 0; index < list.size();index ++){
arr[index] = list.get(index);
}
int year = Integer.parseInt(arr[0].substring(0, 4));
int month = Integer.parseInt(arr[0].substring(4, 6));
int day = Integer.parseInt(arr[0].substring(6, 8));
System.out.println(day);
int days = getAllDays(year);
days = days + getDays(year, month, day);
judge(days);
}
//将数据保存在in.txt文件中,程序读入文件进行判定
private static List<String> transferFile() throws Exception {
FileReader src = new FileReader("src/in.txt");
BufferedReader br = new BufferedReader(src);
List<String> date = new ArrayList<>();
String str = null;
while((str = br.readLine()) != null) {
if(str != null) {
date.add(str);
}
//System.out.println(str);
}
for (String string : date) {
String[] arr = string.split("-");
for (String str1 : arr) {
System.out.println(str1);
}
}
br.close();
return date;
}
//将输出结果保存至out.txt文件中
private static void leadin(String str) throws Exception {
FileWriter out = new FileWriter("src/out.txt");
BufferedWriter bw = new BufferedWriter(out);
bw.write(str);
bw.newLine();
bw.close();
}
}
五,程序流程图
六.程序测试与调试过程
通过judgeDate()方法输入日期,判断日期的写法已被弃用,且不能使用文件进行数据测试。
调试:使用文件进行数据测试。如将日期数据保存在in.txt文件中,程序读入in.dat文件进行判定,并将结果输出至out.txt文件