1.用for循环、switch
以1990.01.01作为参考
public class Demo_9 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("输入年、月(如:2020 01):");
int year = scan.nextInt();
int month = scan.nextInt();
int daysum = 0; // 天数加和
int week = 0; //初始化星期
//判断闰年,并将每年的天数相加
for (int i = 1990; i < year; i++) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
daysum += 366;
} else {
daysum += 365;
}
}
//用循环将最后一年每个月天数相加
for (int i = 1; i < month; i++) {
switch (i) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysum += 31;
break;
case 2:
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
daysum += 29;
break;
} else {
daysum += 28;
break;
}
default:
daysum += 30;
}
}
//储存所查询的当前月的天数
int day = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 2:
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
day = 29;
break;
} else {
day = 28;
break;
}
default:
daysum += 30;
day = 30;
}
week = daysum % 7 + 1; //计算当前月的一号星期几
//制作日历
System.out.println("一\t二\t三\t四\t五\t六\t日\t");
for (int i = 1; i < day + week; i++) {
if (i < week) {
System.out.print("\t");
} else {
if ((i - 1) % 7 == 0) {
System.out.println();
}
System.out.print((i - week + 1) + "\t");
}
}
}
}
2.将重复的代码封装调用
public class Demo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("请输入 年 月(2000 1):");
int year = scan.nextInt();
int month = scan.nextInt();
int daysum = dayForMonth(year, month);
int week = dayForYear(year, month) % 7 + 1;
if (year < 1990) {
System.out.println("抱歉!1990年以前暂不支持!!!");
return;
}
if (daysum < 0) {
System.out.println("输入的月份有误,请重新输入!");
return;
}
System.out.println("\t\t" + " " + year + "年" + month + "月");
System.out.println("一\t二\t三\t四\t五\t六\t日\t");
for (int i = 1; i <= daysum + week - 1; i++) {
if (i < week) {
System.out.print("\t");
} else {
System.out.print(i - (week - 1) + "\t");
if (i % 7 == 0) {
System.out.println("\n");
}
}
}
}
// 闰年的判断
public static boolean isLeapYear(int year) {
if (year % 400 == 0 || year % 4 == 0 && year % 400 == 0) {
return true;
} else {
return false;
}
}
// 每个月的天数
public static int dayForMonth(int year, int month) {
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
}
return -1;
}
// 从参考值到所求值的天数
public static int dayForYear(int year, int month) {
int day = 0;
for (int i = 1990; i < year; i++) {
if (isLeapYear(i)) {
day += 366;
} else {
day += 365;
}
}
for (int i = 0; i < month; i++) {
day += dayForMonth(year, i);
}
return day;
}
}
3.总结
对于第一种方法,将一些代码重复使用,书写麻烦,观看不简洁。
对于第二种,将重复使用的代码进行封装,直接调用,程序出错修改方便。
小白还是第一次写博客,作为一名Java的初学者,在写第一种方法时,知识存储量不够,另外思维不够严谨,没有将出错情况编写进入,输入错误的数据也会出现答案,小白将自己的学习过程发出来,希望各位大佬们指点,一起加油进步。