简单日历的实现
-
内容介绍:输入想要显示的年份以及相应月份,输入完成后在控制台中打印出日历。
-
代码实现以及相应流程细节的介绍:
代码:
/** * 简单日历的实现: * 输入所要查找的年分以及月份, * 就可以打印出该年该月份的日历。 * * */ public class Calendar { private int year; private int month; Scanner in = new Scanner(System.in); String[] str = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二" }; public Calendar() { getDate(); } public void getDate() { //获取输入的年和月。 System.out.println("请输入年份和月份:"); year = in.nextInt(); month = in.nextInt(); } public int ReMonDays() { //返回该月的天数 int days = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 4: case 6: case 9: case 11: days = 30; break; case 2: if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { days = 29; } else { days = 28; } break; } return days; } public int getMonFirst() { /*计算思路: int redays = 1; *1.days用于记录输入月份前每一个月份的天数。 int days = 0; *2.redays用于记录输入月份第一天的天数。 for (int i = 0; i < month; i++) { *3.首先redays初始化为1,(一月份第一天 switch (i) { *即为本年第一天,加上所求月份前几个月份天数总和n case 1: *n+1即为输入月份在本年中的第n+1天。 case 3: */ case 5: case 7: case 8: case 10: case 12: days = 31; break; case 4: case 6: case 9: case 11: days = 30; break; case 2: if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { days = 29; } else { days = 28; } break; } redays += days; //循环结束后redays即为输入月份第一天在本年中的第redays天 } return ((year - 1) + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400 + redays) % 7; //计算出输入月份第一天的星期数并返回。 //共返回七种情况:1,2,3,4,5,6,0对应 } //一 二 三 四 五 六 日 public void show() { //记录输入的月份第一天的星期数 int weekday = getMonFirst(); //记录本月份的天数 int days = ReMonDays(); // 绘制日历表头:表头间隔为四个空格 System.out.printf(" %s 月 \n", str[month - 1]); System.out.print("一 二 三 四 五 六 日\n"); //根据变量weekday控制“ ”输出的长度来使每一天对应所在星期 //" "共包含由四个空格 for (int i = 0; i < (weekday != 0 ? (weekday - 1) : 6); i++) { System.out.print(" "); } //打印各天 for (int i = 1; i <= days; i++) { if (i < 10) System.out.printf("0%d ", i); else System.out.printf("%d ", i); if ((weekday + i - 1) % 7 == 0) { //到达星期天后换行 System.out.println(); } } } public static void main(String[] args) { Calendar c = new Calendar(); c.show(); } }
显示样例: