算法初级_Question3_打鱼还是晒网(java实现)

这篇文章讲述的是算法初级部分的打鱼还是晒网问题的java实现,参考的书籍为清华大学出版社出版,贾蓓等编著的《c语言趣味编程1000例》,如有错误或者不当之处,还望各位大神批评指正。

问题描述

问题描述:三天打鱼两天晒网,某人从1990年1月1日起开始三天打鱼两天晒网,问之后的某一天是打鱼还是晒网?

算法分析

  1. 计算1990年1月1日到指定日期共有多少天
  2. 打鱼晒网的周期模5便可知道改天是打鱼还是晒网
  3. 若模5的结果为1,2,3则为打鱼,其余为晒网

代码实现

class Date {
    int year ;
    int month ;
    int day ;
}


public class Q3_Fishing {
    /**
     * 问题描述:三天打鱼两天晒网,某人从1990年1月1日起开始三天打鱼两天晒网,问之后的某一天是打鱼还是晒网?
     * 
     * 算法分析:1. 计算1990年1月1日到指定日期共有多少天
     *          2. 打鱼晒网的周期模5便可知道改天是打鱼还是晒网
     *          3. 若模5的结果为1,2,3则为打鱼,其余为晒网
     */

    public static void main(String[] args) {

        Date date = new Date() ;
        int totalDay ;
        int result ;

        System.out.println("请输入日期(年 月 日):");
        Scanner scanner = new Scanner(System.in);
        int year = scanner.nextInt() ;
        int month = scanner.nextInt() ;
        int day = scanner.nextInt() ;
        scanner.close();

        date.year = year ;
        date.month = month ;
        date.day = day ;

        totalDay = countDay(date) ;
        System.out.println(totalDay);
        result = totalDay%5 ;

        //结果判定
        if(result >= 1 && result <= 3 )
            System.out.println("今天打鱼");
        else{
            System.out.println("今天晒网");
        }

    }
    /***
     * 计算日期到1990年1月1日到指定日期的天数
     */
    private static int countDay(Date date) {
        // TODO Auto-generated method stub
        int totalDay = 0 ;
        int preMonth[] = {0,31,28,31,30,31,30,31,31,30,31,30,31} ;

        if(isLeapYear(date.year))
            preMonth[2] += 1 ;

        for(int i = 1990 ; i<date.year ; ++i){
            if(isLeapYear(i))
                totalDay += 366 ;
            else
                totalDay += 365 ;
        }

        for(int i=1 ; i<date.month ;++i){
            totalDay += preMonth[i] ;
        }

        totalDay += date.day - 1 ;  //注意这里要减去一天因为初始值为1,加上不符合逻辑

        return totalDay ;
    }
    /**
     * 闰年判定
     */
    private static boolean isLeapYear(int year){
        boolean isLeapYear = false ; //闰年标识
        if(year%400 == 0 || (year%4 ==0 && year%100 !=0) )//闰年判定
            isLeapYear = true ;
        return isLeapYear ;
    }

}

样例输出

  • 输入
2012 1 30
  • 输出
今天晒网

猜你喜欢

转载自blog.csdn.net/u013634252/article/details/80813600