import java.util.Scanner;
public class Main {
//判断给定的年份是否为闰年,true:闰年;false:平年
//判断方法:闰年年份需满足:能被4整除且能被100整除||能被400整除
public boolean isLeapYear(int year){
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
//根据指定年份和月份求出该月份的天数
public int getMonthDay(int year,int month){
int total = 0;
switch(month){
case 1: total = 31;break;
case 3: total = 31;break;
case 5: total = 31;break;
case 7: total = 31;break;
case 8: total = 31;break;
case 10: total = 31;break;
case 12: total = 31;break;
case 4: total = 30;break;
case 6: total = 30;break;
case 9: total = 30;break;
case 11: total = 30;break;
case 2: if(isLeapYear(year))//2月单独进行判断
{total = 29;}
else
{total = 28;}
break;
}
return total;
}
//判断某一年第一天星期几
public int getFirtdayOfYear(int year) {
int total = 0;
int YearDay = 0;
for(int i=1;i<year;i++) //从公元1年1月1日星期一开始计日
{ //计算到指定年份的总天数
if(isLeapYear(i))
{YearDay = 366;}
else
{YearDay = 365;}
total += YearDay;
}
return total%7+1;//总天数对7取余再加1即为星期数
}
//判断某一年某一月第一天星期几
public int getFirtdayOfMonth(int year,int month) {
int FirtdayOfYear = getFirtdayOfYear(year);
int total = FirtdayOfYear;
for(int i=1;i<month;i++)
{
total += getMonthDay(year,i);
}
return total%7;
}
//输出日历表
public void showCalender(int year,int month) {
//制作表头
System.out.println("\t\t\t"+year+"年"+month+"月");
System.out.println("......................................................");
System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
//输出并记录每月第一天之前的空白天的数
int blank =getFirtdayOfMonth(year,month);
int cnt=0;
for(int i=1;i<= blank;i++){
System.out.print("\t");
cnt++;
}
//输出日历
for(int i=1;i<=getMonthDay(year,month);i++){
System.out.print(i+"\t");
cnt++;
//若记录空白数和日期数的和是七的倍数,要换行输出
if(cnt % 7 == 0){
System.out.println();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("请输入年份");
int year = in.nextInt();
System.out.println("请输入月份");
int month = in.nextInt();
Main test = new Main();
test.showCalender(year,month);
}
}
Java实现万年历
于 2021-12-12 15:25:50 首次发布