1. 程式人生 > >使用java 打印日歷

使用java 打印日歷

ear nth rate gen imp bsp 輸入 args urn

package hangshu;

/*

  * 打印從1900年到2、year年的日歷

*/

import java.util.Scanner;

public class Calender {

  public static int year = Integer.MIN_VALUE;

  public static int month = Integer.MIN_VALUE;

  private static int[] m = {31,28,31,30,31,30,31,31,30,31,30,31};

  public static void main(String[] args) {

         // TODO Auto-generated method stub

    InputYearAndAay(); //輸入年月

    printBiaotou(); //打印表頭

    printCanlender(); //打印日歷

  }

//打印日歷

private static void printCanlender() {

  int sum=getSumYear();

   sum+=getSumMonth();

  int count = sum%7;

   for(int i=0;i<=count-1;i++)

  System.out.print("\t");

  for(int i=1;i<=m[month-1];i++)

  {

     System.out.print(i+"\t"); if(sum%7 == 6) System.out.print("\n"); sum++;

   }

}

//計算year總天數

private static int getSumYear(){

   int sum = 0;

  for(int i=1900;i<year;i++)

    {

      sum+=365;

      if(Judge(year))

      sum++;

    }

  return sum;

}

//計算month的總天數

private static int getSumMonth() {

  int sum = 0;

  for(int i=0;i<month-1;i++)

  {

     sum+=m[i];

  }

  if(Judge(year) && month>2)

    sum++;

    sum++; //要計算1900年到year年month—1的天數

    return sum;

    }

//打印表頭

private static void printBiaotou() {

  String[] mon = {"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};

  String[] week = {"星期一 ","星期二 ","星期三 ","星期四 ","星期五 ","星期六 ","星期日"};

  System.out.println(year+"年"+" "+mon[month-1]); for(int i=0;i<7;i++)

  System.out.print(week[i]+"\t");

  System.out.println();

}

//輸入年月

private static void InputYearAndAay(){

  Scanner input = new Scanner(System.in);

  System.out.print("請輸入年份:");

  year = input.nextInt();

  System.out.print("請輸入月份:");

  month = input.nextInt();

  input.close();

  input = null;

}

//判斷是否閏年

private static boolean Judge(int year) {

  return year%4 == 0 && year%100 != 0 || year%400 == 0;

}

}

使用java 打印日歷