java基础小程序—万年历

时间:2024-01-27 13:30:31
package day02.xiangmu.wannianli;

import java.util.Scanner;

public class CalendarTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("请输入年份:");

        int year = sc.nextInt();

        System.out.println("请输入月份:");

        int month = sc.nextInt();
//计算数据
        //年份的总天数
        int allDays = 0;
        for (int i =1900;i<year;i++){
            if ((i%400==0) || (i%4==0 && i%100!=0))
                allDays+=366;
            else
                allDays+=365;
        }

        //月份的总天数
        int days = 0;
        for (int i = 1;i<=month;i++){
            //判断月份,用switch,只储存一个月的天数
            switch (i){
                case 1: case 3: case 5: case 7: case 8: case 10: case 12:
                    days = 31;
                    break;
                case 4: case 6: case 9: case 11:
                    days = 30;
                    break;
                case 2:
                    if ((year % 400 == 0)||(year%4 ==0 && year % 100 != 0))
                        days = 29;
                    else
                        days = 28;
                    break;
            }
            if (i<month)
            allDays+=days;
        }

        //计算月前的空白格
        int temp = (allDays+1)%7;

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

        //打印空白
        for (int i = 1;i<= temp;i++)
            System.out.print("\t");


        //输出月份天数
        for (int i= 1;i<=days;i++){
            System.out.print(i+"\t");
            //换行
            if ((allDays + i)%7==6)
                System.out.println();
        }





    }
}