Java程序之日历显示

import java.util.Scanner;

public class Calendar {

public static void main(String[] args) {
	// 输入年份和月份
	Scanner scn = new Scanner(System.in);
	System.out.print("请输入要输出月历的年份和月份:");
	int year = scn.nextInt();
	int month = scn.nextInt();
	// 计算指定年份月份的1号到1900年1月1日的天数
	int totalDays = 0;
	// 1、求出1900年1月1日到指定年份的1月1日的整年的天数:使用循环
	for (int i = 1900; i < year; i++) {
		if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
			totalDays += 366;
		} else {
			totalDays += 365;
		}
	}
	// 2、求出指定年份1月1日到指定年份月份1日的天数,使用switch穿透
	switch (month) {
	case 12:
		totalDays += 30;// 11月的天数
	case 11:
		totalDays += 31;// 10月的天数
	case 10:
		totalDays += 30;
	case 9:
		totalDays += 31;
	case 8:
		totalDays += 31;
	case 7:
		totalDays += 30;
	case 6:
		totalDays += 31;
	case 5:
		totalDays += 30;
	case 4:
		totalDays += 31;
	case 3:
		if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
			totalDays += 29;
		} else {
			totalDays += 28;
		}
	case 2:
		totalDays += 31;
	}
	// 推算指定年份月份1号的星期,1代表星期1,7代表星期天
	int weekday = totalDays % 7 + 1;
	System.out.println("计算出的星期为:" + weekday);
	// 算出当月的天数
	int monthsDay = 31;
	if (month == 4 || month == 6 || month == 9 || month == 11) {
		monthsDay = 30;
	} else if (month == 2) {
		if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
			monthsDay += 29;
		} else {
			monthsDay += 28;
		}
	}
	// 输出
	// 1、输出表头
	System.out.println("星期一\t星期二\t星期三\t星期四\t星期五\t星期六\t星期日");
	// 输出前面的空格?空格有几个
	for (int i = 0; i < weekday - 1; i++) {
		System.out.print("\t");
	}
	// 接着开始输出日期
	for (int i = 1; i <= monthsDay; i++) {
		System.out.print(i + "\t");
		if ((i + weekday - 1) % 7 == 0) {
			System.out.println();
			}
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值