代码如下,分析如图,就不在赘述了。
import java.util.Scanner;
public class CalendarDemo {
public static void main(String[] args) {
// 提示输入语句
System.out.println("输入年");
Scanner input = new Scanner(System.in);
int year = input.nextInt();
System.out.println("输入月份");
int month = input.nextInt();
// 2获取1900年距离当前年的天数
int totalDays = CalendarDemo.getFormNwoYearTo1900TotalDays(year);
// 3 获取当前年月份距离1.1的天数
int totalDaysFromMonth = getNowYearPassedTotalDays(year, month);
// 4 相加俩个总天数,计算星期数 从0开始,0是周末, 周123456
int week =(( totalDays +totalDaysFromMonth )+1)%7;
formatCalendarOutPut(week,year, month);
}
// 判断是否闰年
public static boolean isLeapYear(int year) {
if(year%4==0&&year%100!=0||(year%400==0)) {
return true;
}else {
return false;
}
}
// 根据月份获取对应的天数。
public static int getNowMonthDays(int year,int month) {
switch(month) {
case 2:
//调用自己写的判断闰年方法
return isLeapYear(year)?29:28;
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
// 定义起始点。
// 获取当前年份距离1900年的总天数
// year
public static int getFormNwoYearTo1900TotalDays(int year) {
// 定义一个变量,统计总天数
int totaldays = 0;
for(int i = 1900; i<year;i++) {
if(isLeapYear(i)) {
totaldays +=366;
}else {
totaldays +=365;
}
}
return totaldays;
}
/*
* 当前月距离当前年丰1.1日的总天数
* year 年份
* month 月
* return 总天数
*
*/
public static int getNowYearPassedTotalDays(int year,int month) {
int totalDays= 0;
for(int i = 1; i<month;i++) {
totalDays +=getNowMonthDays(year, i);
}
return totalDays;
}
//格式化输出日历
//年份:year
//月份:moth
//周几:week
public static void formatCalendarOutPut(int week,int year,int month) {
int count = 0;
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六 ");
// 打印空白
for(int i = 1;i<=week;i++) {
System.out.print("\t");
count ++;
}
// 打印七个之后 换行
for(int i = 1;i<=getNowMonthDays(year, month);i++) {
System.out.print(i+"\t");
count++;
if(count%7==0) {
System.out.println();
}
}
}
}
结果如下: