效果如图
![](https://i-blog.csdnimg.cn/blog_migrate/287c752f931a0ad3153dccb186659fd8.png)
完整代码
public static void calanderSuccess() {
Scanner sca = new Scanner(System.in);
System.out.println("实现万年历效果");
System.out.println("**********欢迎使用万年历**********" + '\n');
System.out.print("请选择年份:(必须要是个正常年份哦!)");
int year = sca.nextInt();
System.out.print("请选择月份:");
if (year <= 0) {
System.out.println("请重新输入年份");
} else {
int month = sca.nextInt();
if (month <= 0 || month > 12) {
System.out.print("请重新输入月份");
} else {
int moon=month;
month = Judgeonth(month, year);
System.out.println("这个月有" + month + "天");
// System.out.println("没思路,不写了");
int yuday = month / 7;
int week = month % 5;
int century = year / 100;
int lst_year=year%100;
System.out.println("世纪"+century+"年"+lst_year);
// 根据蔡勒公式,计算每月第一天
int month_1 = ((lst_year + (lst_year / 4) + (century / 4) - 2 * century + (26 * (moon + 1) / 10) + 1 - 1) )% 7;
System.out.println("礼拜" + month_1);
System.out.println(((26 * (moon + 1) / 10) + 1 - 1) );
int cd = 0;
System.out.println("星期日" + "\t" + "星期一" + "\t" + "星期二" + "\t" + "星期三" + "\t" + "星期四" + "\t" + "星期五"
+ "\t" + "星期六" + "\t");
cd= JudgeSpace(month_1 , cd);
for (int z = 1; z <= month; z++) {
cd++;
System.out.print(z + "\t");
if (cd%7==0) {
System.out.println();
}
}
}
}
}
//判断闰年
public static boolean JudgeRunNian(int year) {
boolean run = true;
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
System.out.println(year + "是闰年");
return run == true;
}
System.out.println(year + "是平年");
return run == false;
}
//判断空格
public static int JudgeSpace(int century, int ct) {
ct = 0;
switch (century) {
case 7:
break;
case 1:
ct = 1;
System.out.print(" \t");
break;
case 2:
ct = 2;
System.out.print(" \t");
break;
case 3:
ct = 3;
System.out.print(" \t");
break;
case 4:
ct = 4;
System.out.print(" \t");
break;
case 5:
ct = 5;
System.out.print(" \t");
break;
case 6:
ct = 6;
System.out.print(" \t");
break;
}
return ct;
}
//判断月份
public static int Judgeonth(int month, int year) {
switch (month) {
case 1:
month = 31;
break;
case 2:
if (JudgeRunNian(year) == true) {
month = 28;
} else {
month = 27;
}
break;
case 3:
month = 30;
break;
case 4:
month = 30;
break;
case 5:
month = 30;
break;
case 6:
month = 31;
break;
case 7:
case 8:
month = 31;
break;
case 9:
month = 30;
break;
case 10:
month = 31;
break;
case 11:
month = 30;
break;
case 12:
month = 31;
break;
}
return month;
}
}
思路:
- 万年历 要判断平闰年 根据平闰年输出二月份的天数,平闰年年份的天数
- 通过 蔡勒公式 输出给定月份的第一天
- 通过判断每月第一天,输出相应空格,然后循环往复剩余天数,顺便在天数加的同时,加个判断,输出七天后就得换行
- 因为第一行的换行是不确定的,所以,我们得弄个计数器,当这个月第一天是礼拜六,那么count就是6了,然后循环的时候count会自加