万年历(方法版)
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("请输入查询的年份:");
int year = scan.nextInt();
System.out.println("请输入查询的月份:");
int month = scan.nextInt();
//获得总天数
int allDay=allDay(year,month);
//获取到查询月第一天的总天数
int day=getDay(year,month);
//确定查询月第一天是星期几
int week=getWeek(allDay);
//打印万年历
printCaleandar(year,month,day,week);
}
//判断是否是闰年
public static boolean isLeapyear(int year){
if(year%4==0 && year%100!=0 || year%400==0){
return true;
}
return false;
}
//获取年的总天数
public static int allDayofyear(int year){
int allDayofyear=0;
for(int a=1900;a<year;a++){
if(isLeapyear(a)){
allDayofyear+=366;
}else{
allDayofyear+=365;
}
}
return allDayofyear;
}
//获取月的总天数
public static int allDayofmonth(int year,int month){
int allDayofmonth=0;
for(int i=1;i<month;i++){
allDayofmonth+=getDay(year,i);
}
return allDayofmonth;
}
//获取当月总天数
public static int getDay(int year,int month){
int day=0;
switch(month){
case 1:case 3:case 5:case 7:case 8:case 10:case 12:
day=31;
break;
case 4:case 6:case 9:case 11:
day=30;
break;
case 2:
if(isLeapyear(year)){
day=29;
}else{
day=28;
}
break;
}
return day;
}
//获取到查询月第一天的总天数
public static int allDay(int year,int month){
int allDay=allDayofyear(year)+allDayofmonth(year,month)+1;
return allDay;
}
//确定查询月第一天是星期几
public static int getWeek(int allDay){
int week=allDay%7;
if(week%7==0){
week=7;
}
return week;
}
//打印万年历
public static void printCaleandar(int year,int month,int day,int week){
if(year<1900 || month<1 || month>12){
System.out.println("输入有问题!!!");
}else{
System.out.println("---"+year+"年"+month+"月---");
System.out.println("一\t二\t三\t四\t五\t六\t日");
int count=0;//换行计数
for(int i=1;i<week;i++){//输出空格
System.out.print("\t");
count++;
}
for(int i=1;i<=day;i++){
System.out.print(i+"\t");
count++;
if(count%7==0){
System.out.println();
}
}
}
}
}
执行结果图: