import java.util.*;
class WNL
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("请输入1900到现在的年数:");
int year = sc.nextInt();
System.out.println("请输入月份:");
int month = sc.nextInt();
//方法的调用
int space = getSum(year,month);
int day = getDay(year,month);
print(space%7,day);
//实现输出上个月与下个月的日历
System.out.println("请输入上个月或下个月的日历:");
String sx = sc.next();
if(sx.equals("上个月")){
int space1 = getSum(year,month-1);
int day1 = getDay(year,month-1);
print(space1%7,day1);
}else if(sx.equals("下个月")){
int space2 = getSum(year,month+1);
int day2 = getDay(year,month+1);
print(space2%7,day2);
}
}
public static int getSum(int year,int month){
//该方法用于封装得到总数的方法,即年+月数
//1,获取到从1900年到现在年的总天数
int allday=0;
for(int i=1900;i<year;i++){
if((i%4==0 && i%100!=0)||i%400==0){
allday+=366;//闰年
}else{
allday+=365;//平年
}
}
//2. 获取1月到month月份的天数
switch(month-1){
case 12:
allday+=31;
case 11:
allday+=30;
case 10:
allday+=31;
case 9:
allday+=30;
case 8:
allday+=31;
case 7:
allday+=31;
case 6:
allday+=30;
case 5:
allday+=31;
case 4:
allday+=30;
case 3:
allday+=31;
case 2:
if((year%4==0&&year%100!=0)||year%400==0){
allday+=29;
}else{
allday+=28;
}
case 1:
allday+=31;
}
return allday+1;
//3.将年数的天数与月份的天数进行相加,得到总天数
}
public static int getDay(int year,int month){
//计算获取天数
int allday=0;
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){
allday+=31;
}else if(month==4||month==6||month==9||month==11){
allday+=30;
}else{
if((year%4==0&&year%100!=0)||year%400==0){
allday+=29;
}else{
allday+=28;
}
}
return allday;
}
public static void print(int space,int day){//print方法封装了日历的打印格式
//打印日期日历的格式
//space表示日历前的空格
//day表示每个月的天数
//day+space表示需要遍历的总数
System.out.println("日\t一\t二\t三\t四\t五\t六");
for(int i=1;i<=(space+day);i++){
if(i<=space){
System.out.print("\t");
}else{
System.out.print((i-space)+"\t");
if(i%7==0){
System.out.println();
}
}
}
}
} |
|