package TengXun;
import java.util.Scanner;
public class Test18 {
public static void main(String[] args) {
//1. 从控制台输入年,月,日,在控制台显示当前月的日历
Scanner scanner = new Scanner(System.in);
// 1.从控制台输入年,月,日
System.out.print("请输入年 月 日:");
int year = scanner.nextInt();
int month = scanner.nextInt();
int day = scanner.nextInt();
// 2.根据年和月计算当月有多少天
int theSameMonthDay = oneMonthDay(year, month);
// 3.根据蔡乐公式计算出星期几
//1582年10月4日后:w = (d + 1+ 2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7;
int week = week2(year, month, 1) - 1;
if (week==-1){
week=6;
}
int week1 = week2(year, month, day);
if (week1 == 0) {
week1=7;
}
System.out.println(year + "年 " + month + "月 " + day + "日 星期" + week1);
// 4.根据当月天数和1号的星期输出日历
System.out.println("一\t二\t三\t四\t五\t六\t日");
int j = 0;
for (int i = 1; i <=theSameMonthDay; i++) {
for (; j < week; j++) {
System.out.print("\t");
}
if (i == day) {
System.out.print("\033[30;31m" + i + "\t" + "\033[0m");
} else
System.out.print(i + "\t");
if ((i + week) % 7 == 0) {
System.out.println();
}
}
}
//判断是否是闰年
public static boolean leapYear(int year) {
return year % 400 == 0 || year % 4 == 0 && year % 100 != 0;
}
//得到一个月有多少天
public static int oneMonthDay(int year, int month) {
int theSameMonthDay;
switch (month) {
case 2:
theSameMonthDay = 28;
if (leapYear(year)) {
theSameMonthDay++;
}
break;
case 4:
case 6:
case 9:
case 11:
theSameMonthDay = 30;
break;
default:
theSameMonthDay = 31;
break;
}
return theSameMonthDay;
}
//得到当月星期几
public static int week2(int year, int month, int day) {
int week2 = (day + 1 + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400) % 7;
return week2;
}
}
运行: