动态日历
简介
根据一个年份一个月份显示当前月份的日历布
代码
灵活运用switch的特点计算总天数,在计算中需考虑平年闰年,大月小月和二月的特殊性
import java.util.Scanner;
public class T2 {
public int n(int y, int m) {
int day = 0;
for (int i = 1901; i <= y; i++) {
if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {
day += 366;
} else if (y > 0) {
day += 365;
}
}
switch (m - 1) {
case 12:
day += 31;
case 11:
day += 30;
case 10:
day += 31;
case 9:
day += 30;
case 8:
day += 31;
case 7:
day += 31;
case 6:
day += 30;
case 5:
day += 31;
case 4:
day += 30;
case 3:
day += 31;
case 2:
if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) {
day += 29;
} else if (y > 0) {
day += 28;
}
case 1:
day += 31;
}
return day;
}
public static void main(String[] args) {
T2 s = new T2();
Test2 e = new Test2();
Scanner in = new Scanner(System.in);
int j = in.nextInt();
int q = in.nextInt();
int day = e.getDayOfMonth(j, q);
int a = s.n(j, q);
int b = a % 7;
int c;
int i;
int sum = b;
if (b > 0) {
for (c = 1; c <= b; c++) {
System.out.print("\t");
}
for (i = 1; i <= day; i++) {
System.out.print(i + "\t");
if ((sum + i) % 7 == 0) {
System.out.println();
}
}
} else {
for (i = 1; i <= day; i++) {
System.out.print(i + "\t");
if ((sum + i) % 7 == 0) {
System.out.println();
}
}
}
}
}
public class Test2 {
public int getDayOfMonth(int y, int m) {
int day = 0;
switch (m) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 2:
if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) {
day = 29;
} else if (y > 0) {
day = 28;
} else {
day = -1;
}
break;
case 4:
case 6:
case 9:
case 11:
day = 30;
break;
default:
day = -1;
}
return day;
}
public static void main(String[] args) {
Test2 d = new Test2();
int day = d.getDayOfMonth(400, 2);
if (day == -1) {
System.out.println("输入错误");
} else {
System.out.println(day);
}
}
}
运行结果
小结
第一次做这道题感觉很麻烦,逻辑很复杂,现在再看感觉自己的代码很杂乱,可以有更好的解决办法,不需要用复杂的switch语句也能解决.