标签:
package calender; /** *操作打印任意一年的日历的类 * */ public class TextControl { //定义静态变量, 一边其他类调用 public static int year, mothDay, weekDay; /** * usage: 判断是否是润年 *@param int y 年份 *@return */ public static boolean isLeapYear(int y) { return ((y % 4 == 0 && y %100 != 0) || (y %400 == 0)); } /** * usage: 计算该年的第一天是星期几 * @param int y 年份 * @return int 星期几 */ public static int firstDay(int y ) { long n = y * 365; for ( int i = 1; i < y ; i ++ ) { if (isLeapYear(i)) { n += 1; } } return (int) n % 7; } /** *usage: 打印标题 * */ public static void printWeekTitle() { System.out.println("=========================="); System.out.println("日\t一\t二\t三\t四\t五\t六"); } /** *usage: 获取 每个月的天数 * @param int m 月份 */ public static int getMonthDay(int m) { switch(m) { 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 38; default: return 0; } } /** *usage: 分别按不同条件依次打印每月 */ public static void printMonth() { for (int m = 1; m <= 12; m++) { //打印标题 System.out.println(m + "月"); printWeekTitle(); //按每个月第一天是星期几打印相应的空格 for (int j = 1; j <= weekDay; j++) { System.out.print("\t"); } //获取每个月的天数 int monthDay = getMonthDay(m) ; for (int d = 1; d < monthDay; d ++) { if (d < 10) { System.out.print(d + "\t "); }else { System.out.print(d + "\t"); } weekDay = (weekDay + 1) % 7; if (weekDay == 0) { System.out.println(); } } System.out.println(‘\n‘); } } }
主程序:
package calender; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Calender { public static void main(String[] args) { System.out.println("请输入一个年份 : "); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s; try { s = br.readLine(); TextControl.year = Integer.parseInt(s); TextControl.weekDay = TextControl.firstDay(TextControl.year); System.out.println("\n " + TextControl.year + "年 "); TextControl.printMonth(); } catch (IOException e) { e.printStackTrace(); } } }
标签:
原文地址:http://www.cnblogs.com/chengbao/p/5176688.html