import java.util.Scanner;
public class Calenderchengming {
/**
* 计算指定月的天数
*/
public int calMonthDay(int year,int month){
int days;
switch (month){
case 2:
if(year%4==0&&year%100!=0||year%400==0){
days=29;
break;
}else {
days=28;
break;
}
case 4:
case 6:
case 9:
case 11:
days=30;
break;
default:
days=31;
break;
}
return days;
}
/**
* 计算给定年月到1900年之间的总天数
* @param year
* @param month
* @return 总天数
*/
public int yearTotoDays(int year,int month){
//给定年到1900年之间的天数
int sumYearTotoDays=0;
for(int i=1900;i<year;i++){
//判断闰年还是平年
if(i%4==0&&i%100!=0||i%400==0){
sumYearTotoDays+=366;
}else {
sumYearTotoDays+=365;
}
}
//计算给定月份之前几个月的总天数
int sunMonthTotoDays=0;
for(int i=1;i<month;i++){
sunMonthTotoDays+=calMonthDay(year, i);
}
int Toto=sumYearTotoDays+sunMonthTotoDays;
return Toto;
}
/**
* 获取输入月份1号是星期几
*/
public int gerWeek(int year,int month){
//获取总天数
int toto=yearTotoDays(year, month);
//获取星期数
int week=(toto+1)%7;
return week;
}
public void show(int year,int month){
int week=gerWeek(year,month);
typeCalender(week,year,month);
}
/**
* 打印日历
*/
public void typeCalender(int week,int year,int month){
System.out.println("日\t一\t二\t三\t四\t五\t六");
int toto=yearTotoDays(year,month);
//根据星期数决定打印几个\t
for(int i=1;i<=week;i++){
System.out.print("\t");
}
//获取当月的天数
int days=calMonthDay(year,month);
//打印输入月份当月的天
for(int i=1;i<=days;i++){
System.out.print(i+"\t");
//如果当天是周六 则换行
if((toto+i)%7==6){
System.out.println();
}
}
}
//主函数
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("输入年份");
int year=scanner.nextInt();
System.out.println("输入月份");
int month=scanner.nextInt();
Calenderchengming calender=new Calenderchengming();
calender.show(year,month);
}
}
javaSE最简单的万年历实现
最新推荐文章于 2024-09-05 11:00:53 发布