Calendar c = Calendar.getInstance();
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份");
int year = sc.nextInt();
System.out.println("请输入月份");
int month = sc.nextInt();
System.out.println("===================日历:【"+year +"】年【" + month +"】月==================");
System.out.println("日" + "\t" + "一" + "\t" + "二" + "\t" + "三" + "\t" + "四" + "\t" + "五" + "\t" + "六");
System.out.println("=====================================================");
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month - 1);
int a = c.getActualMaximum(Calendar.DAY_OF_MONTH);
// int a = c.getFirstDayOfWeek() ;
// System.out.println(a);
c.set(Calendar.DAY_OF_MONTH, 1);
int count = c.get(Calendar.DAY_OF_WEEK) - 1;
for(int i = 0; i < count; i++) {
System.out.print(" " + "\t");
}
for(int i = 0; i < a; i++) {
if((i + c.get(Calendar.DAY_OF_WEEK)) % 7 == 0 || (i + c.get(Calendar.DAY_OF_WEEK)) % 7 == 1) {
System.out.print("【" + (i + 1) + "】" + "\t");
}else {
System.out.print(i + 1 + "\t");
}
count++;
if(count == 7) {
System.out.println();
count = 0;
}
}
思路:先利用Calendar类中方法得到输入月份有多少天数,然后得到这个月第一天,根据这两个数据便可得到一个动态日历,最后将这些数据打印到控制