输入 年 月 日 打印动态日历

 

package TengXun;

import java.util.Scanner;

public class Test18 {
    public static void main(String[] args) {
        //1. 从控制台输入年,月,日,在控制台显示当前月的日历
        Scanner scanner = new Scanner(System.in);
        // 1.从控制台输入年,月,日
        System.out.print("请输入年 月 日:");
        int year = scanner.nextInt();
        int month = scanner.nextInt();
        int day = scanner.nextInt();
        // 2.根据年和月计算当月有多少天
        int theSameMonthDay = oneMonthDay(year, month);

        // 3.根据蔡乐公式计算出星期几
        //1582年10月4日后:w = (d + 1+ 2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7;
        int week = week2(year, month, 1) - 1;
        if (week==-1){
            week=6;
        }
        int week1 = week2(year, month, day);
        if (week1 == 0) {
            week1=7;
        }
            System.out.println(year + "年 " + month + "月 " + day + "日 星期" + week1);


        // 4.根据当月天数和1号的星期输出日历
        System.out.println("一\t二\t三\t四\t五\t六\t日");
        int j = 0;
        for (int i = 1; i <=theSameMonthDay; i++) {
            for (; j < week; j++) {
                System.out.print("\t");
            }
            if (i == day) {
                System.out.print("\033[30;31m" + i + "\t" + "\033[0m");
            } else
                System.out.print(i + "\t");
            if ((i + week) % 7 == 0) {
                System.out.println();
            }
        }
    }

    //判断是否是闰年
    public static boolean leapYear(int year) {
        return year % 400 == 0 || year % 4 == 0 && year % 100 != 0;
    }

    //得到一个月有多少天
    public static int oneMonthDay(int year, int month) {
        int theSameMonthDay;
        switch (month) {
            case 2:
                theSameMonthDay = 28;
                if (leapYear(year)) {
                    theSameMonthDay++;
                }
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                theSameMonthDay = 30;
                break;
            default:
                theSameMonthDay = 31;
                break;
        }
        return theSameMonthDay;
    }

    //得到当月星期几
    public static int week2(int year, int month, int day) {
        int week2 = (day + 1 + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400) % 7;
        return week2;
    }
}

运行:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值