万年历:输入一个年份,再输入一个月份,把那个月的日历打印出来

该文章描述了一个Java程序,用户输入年份和月份后,程序会计算并打印出该月的日历,包括星期数和每个月的天数,以1900年1月1日为基准确定星期。
摘要由CSDN通过智能技术生成

需求:输入一个年份,再输入一个月份,把那个月的日历打印出来
线索:1900年1月1日是星期一

        public static void main(String[] args){

		Scanner scan = new Scanner(System.in);
		
		System.out.println("请输入年:");
		int year = scan.nextInt();//2024
		System.out.println("请输入月:");
		int month = scan.nextInt();//3
		
		//计算年的总天数
		int allDayOfYear = 0;
		for(int i = 1900;i<year;i++){
			if(i%4==0 && i%100!=0 || i%400==0){//闰年
				allDayOfYear += 366;
			}else{//平年
				allDayOfYear += 365;
			}
		}
		
		//计算月的总天数
		int allDayOfMonth = 0;
		for(int i = 1;i<month;i++){
			switch(i){
				case 1:case 3:case 5:case 7:case 8:case 10:case 12:
					allDayOfMonth += 31;
				break;
				case 4:case 6:case 9:case 11:
					allDayOfMonth += 30;
				break;
				case 2:
					if(year%4==0 && year%100!=0 || year%400==0){//闰年
						allDayOfMonth += 29;
					}else{//平年
						allDayOfMonth += 28;
					}
				break;
			}
		}
		
		//合并总天数(1900.1.1 ~ year.month.1)
		int allDay = allDayOfYear + allDayOfMonth + 1;
		
		
		//计算当月第一天的星期数
		int week = allDay%7;
		if(week == 0){
			week = 7;
		}
		
		//获取当月的天数
		int day = 0;
		switch(month){
			case 1:case 3:case 5:case 7:case 8:case 10:case 12:
				day = 31;
			break;
			case 4:case 6:case 9:case 11:
				day = 30;
			break;
			case 2:
				if(year%4==0 && year%100!=0 || year%400==0){//闰年
					day = 29;
				}else{//平年
					day = 28;
				}
			break;
		}
		
		//打印日历
		System.out.println(year + "年" + month + "月");
		System.out.println("一\t二\t三\t四\t五\t六\t日");
		
		int count = 0;//换行的变量
		
		//打印空格
		for(int i = 1;i<week;i++){
			System.out.print("\t");
			count++;
		}
		
		//打印日期
		for(int i = 1;i<=day;i++){
			System.out.print(i + "\t");
			count++;
			if(count % 7 == 0){
				System.out.println();//换行
			}
		}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值