( 显示日历)编写程序,提示用户输人年份和代表该年第一天是星期几的数字,然后在控制台上
显示该年的日历表。
例如,如果用户输入年份 2013 和代表 2013 年 1 月 1 日为星期二的 2, 程
序应该显示该年每个月的日历,如下所示:
import java.io.*;
public class calendar {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 提醒输入,并获取输入结果
System.out.println("Enter a year:");
String year_str = br.readLine();
System.out.println("Enter the first day of this year(Example: 0 as Sun, 1 as Mon, 2 as Tue):");
String day_str = br.readLine();
// 将字符串格式转化为整型
int year = Integer.parseInt(year_str); // 这是几几年
int day = Integer.parseInt(day_str); // 第一天是星期几
boolean tf;
if (year % 4 == 0)
tf = true; // 判断平年闰年用的,判断是否符合四的倍数,即闰年
else
tf = false;
int days = 0;
for (int month = 1; month <= 12; month++) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
days = 31; // 一三五七八十腊,三十一天永不差
else if (month == 2 && tf == true) //
days = 29;
else if (month == 2 && tf == false) // 二月二九或二八
days = 28;
else
days = 30; // 四六九冬三十整
// 打印日历题头
if (month == 1)
System.out.println(" " + "January " + year);
else if (month == 2)
System.out.println(" " + "February " + year);
else if (month == 3)
System.out.println(" " + "March " + year);
else if (month == 4)
System.out.println(" " + "April " + year);
else if (month == 5)
System.out.println(" " + "May " + year);
else if (month == 6)
System.out.println(" " + "June " + year);
else if (month == 7)
System.out.println(" " + "July " + year);
else if (month == 8)
System.out.println(" " + "August " + year);
else if (month == 9)
System.out.println(" " + "September " + year);
else if (month == 10)
System.out.println(" " + "October " + year);
else if (month == 11)
System.out.println(" " + "November " + year);
else if (month == 12)
System.out.println(" " + "December " + year);
System.out.println("————————————————————————————————————————————————————");
System.out.println("Sun\tMon\tTue\tWed\tThu\tFri\tSat"); // 打印日历标引
for (int j=0; j < day; j++) {
System.out.print(" " + "\t"); // 利用月初是星期几的数据输出每个月份日历前的空格,并且不换行
}
for (int i = 1; i <= days; i++) {
if (i == days)
System.out.println(" " + i + "\t\n"); // 最后一天打印完直接换行
else if ((i + day) % 7 == 0)
System.out.println(" " + i + "\t\n"); // 逢周六就打印完换行
else
System.out.print(" " + i + "\t"); // 其他时候打印完接着打就行
}
day = (day + days) % 7; // 更新月初为星期几的数据
}
}
}
// 1582年的日历不能打印(1582年10月换历),其他年份日历均可以