最近想到大学期间写的一个万年历小程序,写出来之后还很自豪。现在想想当时的程序逻辑混杂,结构紊乱,就在空闲时间重新写了个。本来以为二十多分钟就能写好了,结果写了一个多小时。。拿出来给我sdu大一的学弟学妹们参考一下吧。
ps:没有加入输入异常的处理,即默认输入正确的年份格式,如:2000。另外,最早查询年份到(含)1950年。
package JustForFun;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class JustForTest {
public static void main(String argus[]) throws IOException {
int year, count = 1, month = 1, index;
System.out.println("输入你想查询的年份,我将输出这一年的日历,嘿嘿");
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
year = Integer.valueOf(reader.readLine());
System.out.println(year + "年的日历:");
index = spaceCount(year)+1;
while (month <= 12) {
System.out.println(month + "月:");
System.out.println("周日 周一 周二 周三 周四 周五 周六");
printSpace(index - 1);
while (count <= daysMonth(month, year)) {
if (count < 10)
System.out.print(count + " ");
else System.out.print(count + " ");
index++;
count++;
if (index == 8) {
index = 1;
System.out.println();
}
}
if (index != 1)
System.out.println();
count = 1;
month++;
}
}
//计算year的i月有多少天
private static int daysMonth(int i, int year) {
int[] month31 = {1, 3, 5, 7, 8, 10, 12};
int[] month30 = {4, 6, 9, 11};
for (int l = 0; l < month31.length; l++) {
if (i == month31[l])
return 31;
}
for (int l = 0; l < month30.length; l++) {
if (i == month30[l])
return 30;
}
if (daysCount(year) == 365)
return 28;
return 29;
}
//每个月从周几开始
private static void printSpace(int count) {
for (int i = 0; i < count; i++)
System.out.print(" ");
}
//计算year有多少天
private static int daysCount(int year) {
if (year % 400 == 0)
return 366;
if (year % 100 == 0)
return 365;
if (year % 4 == 0)
return 366;
return 365;
}
//输入年份的一月从周几开始
private static int spaceCount(int year) {
int years = year - 1950;
int days = 0;
for (int i = 0; i < years; i++) {
days += daysCount(1950 + i);
}
return days % 7;
}
}