Java打印年月日曆

一.功能

根據用戶輸入的年份和月份,在控制檯打印出對應月份的日曆。

二.算法講解

要打印一個月的日曆只需要知道兩件事。

1.這個月第一天是星期幾

本例子中,使用蔡勒公式,判斷某年某月的一號是周幾,關於蔡勒公式不瞭解的同學可以百度一下,這裏不作講解。
使用"蔡勒公式"計算某月第一天是周幾的好處有:
​(1).不用選擇參考年月日;
(2)不用計算參考日到計算日的間隔天數;
(3)不用計算一年有多少天。

2.這個月有多少天

使用switch-case語句進行判斷,大月31天,小月30天,2月閏年29天,平年28天。

三.源碼

import java.util.Scanner;
public class DateUtils{

 /*判斷是否爲閏年*/
  public boolean isleap(int year){
   return (year%4==0)&&(year%100!=0)||year%400==0;
  }
  /*判斷這個月有多少天*/
  public int daysOfmonth(int year,int month){
   switch(month){
   /*大月*/
   case 1:
   case 3:
   case 5:
   case 7:
   case 8:
   case 10:
   case 12:
    return 31;
  /*小月*/
   case 4:
   case 6:
   case 9:
   case 11:
    return 30;
  /*二月*/
   case 2:if(isleap(year)) return 29;
          else return 28;
   default:
    System.out.println("程序錯誤:輸入的月份有誤!");
    return 0;
   }
  }
/**
     * 蔡勒公式,判斷某年某月的一號是周幾
     * @param year 年
     * @param month 月
     * @return week(0,6)
     */
    private int weekOffirst(int year,int month){
        int m=month;
        int d=1;
        if(month<=2){ /*對小於2的月份進行修正*/
            year--;
            m=month+12;
        }
        int y=year % 100;
        int c=year/100;//世紀數減1
        int w=(y+y/4+c/4-2*c+(13*(m+1)/5)+d-1)%7;
        if(w < 0) /*修正計算結果是負數的情況*/
            w+= 7;
        return w;
    }
     /*打印日曆*/
     public void dataprint(int year,int month){
      System.out.println("\t\t"+year+"年"+" "+month+"月");
      System.out.println("日\t一\t二\t三\t四\t五\t六");
      int week=weekOffirst(year,month);
      int[][] data = new int[6][7] ;
      int daynum=1;
      for(int i=0;daynum<=daysOfmonth(year,month);i++){
       for(int j=0;j<7&&daynum<=daysOfmonth(year,month);j++){
        if(i==0&&j<week) {
         data[i][j]=0;
         System.out.print("\t");
        }
        else {
         data[i][j]=daynum++;
         System.out.print(data[i][j]+"\t");
        }
       }System.out.println();
      }
     }
     /*主函數入口*/
     public static void main(String[] args){
      DateUtils du=new DateUtils();
      Scanner scn=new Scanner(System.in);
      System.out.print("輸入要打印的年:");
      int year=scn.nextInt();
      System.out.print("輸入要打印的月:");
      int month=scn.nextInt();
      scn.close();
      du.dataprint(year, month);
     }
}

效果預覽

2020年1月

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章