知识点:
1.闰年的计算方式((year % 4 ==0 && year % 100 != 0 )|| year % 400 ==0)
闰年二月份有 29天 平年28 年
public static void main(String[] args) {
/*
获取用户输入的日期
*/
Scanner scan = new Scanner(System.in);
System.out.println("请输入年份:");
int year = scan.nextInt();//存储年份
System.out.println("请输入月份:");
int month = scan.nextInt();//存储月份
System.out.println("请输入日期:");
int date = scan.nextInt();//存储日期
int monthOfDay = 0;//月份总天数
int allDays = 0;//总天数
int week = 0;//存储每月第一天是星期几
/*
输出月历,每个星期一行,从星期日开始至星期六结束
*/
System.out.println("=========="+year+"年"+month+"月份"+date+"日"+"=========");
System.out.println("");
System.out.println("");
System.out.println("");
/*月历核心代码开始*/
//判断本月一号为星期几;1900年1月1日为星期一
//获取1900年到用户输入的年份的总天数
for (int i = 1900;i<=year;i++){
if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0){
allDays += 366;//闰年 每年则有366天
}else{
allDays += 365;//平年 每年则有365天
}
}
//获取用户输入年份+月份的天数
for (int j = 1;j<month;j++){
switch (j){
case 2:if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
allDays += 29;
}else {
allDays +=28;
}
break;
case 1: case 3: case 5: case 7: case 8: case 10: case 12:allDays += 31;
break;
default:allDays +=30;
break;
}
}
week = allDays % 7;
int n;
switch (month){
case 2: if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
monthOfDay = 29;
}else {
monthOfDay = 28;
}
case 1: case 3: case 5: case 7: case 8: case 10: case 12:monthOfDay = 31;break;
default:monthOfDay = 30;break;
}
System.out.println(year+"年"+month+"月"+" 月历展示");
System.out.println("日\t一\t二\t三\t四\t五\t六");
for (int i = 1; i <= week; i++) { //满足条件,先\t,如果week=0;则不打印
System.out.print("\t");
}
for ( n = 1; n <= (7 - week); n++) { //打印月历的第一行
System.out.print(n + "\t");
}
System.out.println(); //月历第一行打印完成,换行打印第二行,光标进入第二行
for (; n <= monthOfDay; n++) { //打印后面的月历的内容
System.out.print(n + "\t");
if ((n + week) % 7 == 0) { //打印到星期日就换行,然后继续打印
System.out.println();
}
}
System.out.println();
/*月历核心代码结束*/
}