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();

           }

       }

      

    }

}

你可能感兴趣的:(算法面试)