1. 程式人生 > >Java實現了一個萬年曆

Java實現了一個萬年曆

import java.util.Scanner;

public class DaysCelandar {

    // 判斷是不是閏月年

    public static boolean isRun(int year) {

       if ((year % 4 == 0 && year % 100 != 0) || year %100 == 0) {

           return true;

       } else {

           return false;

       }

    }

    // 統計輸入年份到1990-1-1的天數

    public static

int dayTotals(int year, int month) {

       int dayTotals = 0;

       for (int i = 1990; i < year; i++) {

           if (isRun(i)) {

              dayTotals += 366;

           } else {

              dayTotals += 365;

           }

       }

       for (int j = 1; j < month; j++) {

           dayTotals += monthTotalDays

(year, j);

       }

       return dayTotals;

    }

    // 判斷指定年的指定月的天數

    public static int monthTotalDays(int year, int month) {

       int monthTotalDays = 31;

       switch (month) {

       case 4:

       case 6:

       case 9:

       case 11:

           monthTotalDays = 30;

       case 2:

           if

(isRun(year)) {

              monthTotalDays = 29;

           } else {

              monthTotalDays = 28;

           }

           break;

       }

       return monthTotalDays;

    }

    // 計算星期幾

    public static void main(String[] args) {

       int year;

       int day;

       int month;

       int days;

       int monthTotals;

       Scanner in = new Scanner(System.in);

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

       year = in.nextInt();

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

       month = in.nextInt();

       //System.out.println(year + "" + month + "");

       System.out.println();

       /*

        *if (isRun(year)) { System.out.println(year + "是閏年"); } else {

        *System.out.println(year + "不是閏年"); }

        */

       monthTotals = monthTotalDays(year, month);

       //System.out.println(year + "" + month + "" + ":" +monthTotals +

       // "");

       days = dayTotals(year, month);

       days++;

       //System.out.println("1990-01-01 到現在共:" + dayTotals + "");

       day = days % 7;

       System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t");

       int count = 0;

       for (int i = 0; i < day; i++) {

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

           count++;

       }

       for (int j = 1; j <= monthTotals; j++) {

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

           count++;

           if (count % 7 == 0) {

              System.out.println();

           }

       }

    }

}