生活中日历随处可见,如何用java写一个简单的日历呢?

          如果我们想要制作一个从1900年到当前年份的日历,并且打印当前年份, 首先我们要知道计算日历需要用到那些数据和知识?

目录

一、获取信息

二、代码实现      

三、内容分析

四、学习总结


一、获取信息

          1、闰年 366 天,平年 365 天
          2、能被 4 整除并且不能被 100 整除或者能被 400 整除的年份就是闰年。
          3、4/6/9/11 月是 30 天,2 月需要判断 2 月所在的年份是否是闰年,闰年的 2
月 29 天,平年的 2 月是 28 天。其他月份 31 天。

          4、每月前的空格计算

 

 

       该空格是从 1900 年到当前年的当前月的前面所有天数加起来对 7 求余数得到
的。比如说现在是 2022 年 2 月前面的天数,从 1900 年~2022 年 1 月 31 号的所有天
数加起来对 7 求余数得到的。 

二、代码实现      

package com.bai.demo;
import java.util.Scanner;
public class Calendar {
    public static void main(String [] args) {
    	//提示语
		System.out.println("请输入想要查询的年份:");
    	//创建一个对象
		Scanner sc=new Scanner(System.in);
		int nowYear=sc.nextInt();
    	sc.close();
		//调用printCalendar方法
    	printCalendar(nowYear);
    }
    //判断是否是闰年
    public static boolean isLeapYear(int year) {
		return (year%4==0&&year%100!=0)||year%400==0;
    }
    //计算月份天数
    public static int countMonthDays(int month,int year) {
    	if(month==4||month==6||month==9||month==11) {
    		return 30;
    	}else if(month==2) {
    		return isLeapYear(year)?29:28;
    	}else{
    		return 31;
    	}
    }
    //计算1900到当前年之前所有年天数之和
    public static int countAllYearDays(int nowYear) {
    	int allYearDays=0;
    	for(int i=1900;i<nowYear;i++) {
    		 allYearDays+=isLeapYear(i)?366:365;
    	}
    	return allYearDays;
    }
    //计算当前年当前月之前所有月份天数之和
    public static int countAllMonthDays(int nowMonth,int nowYear) {
    	int allMonthDays=0;
    	for(int i=1;i<nowMonth;i++) {
    		allMonthDays+=countMonthDays(i,nowYear);
    	}
		return allMonthDays;
	}
    //打印
    public static void printCalendar(int nowYear) {
    	int allYearDays=countAllYearDays(nowYear);
    	for(int i=1;i<=12;i++) {
    	   //打印月份
    	   System.out.println("\t\t\t"+i+"月\n");
    	   //打印星期
    	   System.out.println("一\t二\t三\t四\t五\t六\t日\n");
    	   //打印空格
    	   int r=(allYearDays+countAllMonthDays(i, nowYear))%7;
		   for(int j=0;j<r;j++) {
			  System.out.print("\t");
		   }
		   //打印号数
		   for(int k=1;k<=countMonthDays(i,nowYear);k++) {
			  if((k+r)%7==0) {
				 System.out.println(k+"\n");
			  }else {
				 System.out.print(k+"\t"); 
			  }
		   }
		   System.out.println();
	    }   
    }
}

 

 

三、内容分析

      这段代码中将 1:判断是否是闰年

                              2:计算指定月份天数

                              3:计算当前年当前月之前所有月份天数

                              4:计算1900年到当前年之前所有天数

                              5:打印

         使用单独的静态方法实现,便于调用。

四、学习总结

       乘风破浪会有时,直挂云帆济沧海

            我认为刚开始学习编程就是要反复的敲代码,一遍又一遍,眼过千遍不如手过一遍,只有熟悉知识点,熟练掌握语法,培养逻辑思维,才能学得更好。


版权声明:本文为qq_56288430原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。