第一次作业
源代码:
package com.baidu.www; import java.io.*; import java.util.Scanner; /** * 问题描述:某人从2010年1月1日起开始“三天打渔,两天晒网”,问在这之后的某一天此人是在打渔还是在晒网? * 输入样例:20100106 * 输出样例:打渔 * 易错点:闰年,验证输入数据格式 */ public class Fishing { public static String Judge(String date){ if(!date.matches("[0-9]{8}")){ //通过使用正则表达式"[0-9]{8}"来匹配八个数字,判定输入格式是否正确 return "您输入的日期格式不符合要求"; } boolean flag=false; int year=Integer.valueOf(date.substring(0,4)); //将输入数据转化为数字类型的年,月,日 int month=Integer.valueOf(date.substring(4,6)); int day=Integer.valueOf(date.substring(6,8)); if(year<2010||month==0||month>12||day==0){ //判断输入年份数值是否正确 return "您所输入的日期错误"; } //判断输入月份数值是否正确 if(((month==1||month==3||month==5||month==7||month==8||month==10||month==12)&&day>31)||((month==4||month==6||month==9||month==11)&&day>30)){ return "您所输入的日期错误"; } if((year%4==0&&year%100!=0)||year%400==0){ //判断平\闰年 flag=true; } if(month==2){ //判断输入日期数值是否正确 if(flag){ if(day>29){ return "您所输入的日期错误"; } } else{ if(day>28){ return "您所输入的日期错误"; } } } //至此,已保证输入日期的格式和数值正确。 //判断“打渔”还是“晒网” int sum=0,i; for(i=2010;i<year;i++){ //计算经历的年积累的日子 if((i%4==0&&i%100!=0)||i%400==0){ sum+=366; } else{ sum+=365; } } for(i=1;i<month;i++){ //计算经历的月积累的日子 if(month==2){ if(flag){ sum+=29; } else{ sum+=28; } } else if(month==4||month==6||month==9||month==11){ sum+=30; } else{ sum+=31; } } sum+=day; //计算本月经历的日 if (sum%5==1||sum%5==2||sum%5==3){ //判断当天是打渔还是晒网 return "打渔"; } else { return "晒网"; } } public static void main(String[] args) { BufferedReader bfr=null; BufferedWriter bfw=null; try{ bfr = new BufferedReader(new FileReader("D:\\test\\in.txt")); //设置输入输出流读\写文件路径 bfw = new BufferedWriter(new FileWriter("D:\\test\\out.txt")); String str = null; while ((str = bfr.readLine()) != null) { //每次读取一行数据,直到所读数据为空(读完) System.out.println(str + ":" + Judge(str)); bfw.write(str+":"+Judge(str)); //每次写入结果文件时都会清空原先数据 bfw.newLine(); bfw.flush(); } } catch (IOException e){ System.out.println("出现IO异常"); } catch (Exception e){ System.out.println("出现其他异常"); } finally { try { if(bfr!=null){ bfr.close(); } if(bfw!=null){ bfw.close(); } } catch (IOException e){ System.out.println("流关闭时出现IO异常"); } catch (Exception e){ System.out.println("流关闭时出现其他异常"); } } } }
算法设计思路:
Judge方法:
测试用例(in.txt文件):
输出结果:
控制台:
out.txt文件: