日历实现代码
簡(jiǎn)單日歷的實(shí)現(xiàn)
內(nèi)容介紹:輸入想要顯示的年份以及相應(yīng)月份,輸入完成后在控制臺(tái)中打印出日歷。
代碼實(shí)現(xiàn)以及相應(yīng)流程細(xì)節(jié)的介紹:
代碼:
/*** 簡(jiǎn)單日歷的實(shí)現(xiàn):* 輸入所要查找的年分以及月份,* 就可以打印出該年該月份的日歷。* **/ 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("請(qǐng)輸入年份和月份:");year = in.nextInt();month = in.nextInt();}public int ReMonDays() { //返回該月的天數(shù) 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() { /*計(jì)算思路:int redays = 1; *1.days用于記錄輸入月份前每一個(gè)月份的天數(shù)。int days = 0; *2.redays用于記錄輸入月份第一天的天數(shù)。for (int i = 0; i < month; i++) { *3.首先redays初始化為1,(一月份第一天switch (i) { *即為本年第一天,加上所求月份前幾個(gè)月份天數(shù)總和ncase 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; //循環(huán)結(jié)束后redays即為輸入月份第一天在本年中的第redays天}return ((year - 1) + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400 + redays) % 7; //計(jì)算出輸入月份第一天的星期數(shù)并返回。 //共返回七種情況:1,2,3,4,5,6,0對(duì)應(yīng)} //一 二 三 四 五 六 日public void show() {//記錄輸入的月份第一天的星期數(shù)int weekday = getMonFirst();//記錄本月份的天數(shù)int days = ReMonDays();// 繪制日歷表頭:表頭間隔為四個(gè)空格System.out.printf(" %s 月 \n", str[month - 1]);System.out.print("一 二 三 四 五 六 日\(chéng)n");//根據(jù)變量weekday控制“ ”輸出的長(zhǎng)度來使每一天對(duì)應(yīng)所在星期//" "共包含由四個(gè)空格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);elseSystem.out.printf("%d ", i);if ((weekday + i - 1) % 7 == 0) { //到達(dá)星期天后換行System.out.println();}}}public static void main(String[] args) {Calendar c = new Calendar();c.show();}}顯示樣例:
總結(jié)
- 上一篇: 百度文库自动评分器
- 下一篇: 漫谈程序员系列:程序员到底是什么角色