Java执行语句综合应用-万年历

万年历

需求:输入年和月,打印当月的日历

线索:1900年1月1日是星期一

	public static void main(String[] args){
		
		//输入年和月 --- 2024.4
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入年:");
		int year = scan.nextInt();
		System.out.println("请输入月:");
		int month = scan.nextInt();
		
		//计算年的总天数 --- 1900~2023
		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;
			}
		}
		
		//计算月的总天数 --- 1~3
		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;
			}
		}
		
		//合并总天数
		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();
			}
		}
		
		
	}
}
  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值