输入 年 月 输出日历
package com.studyJava.calender; import java.util.Scanner; /** * 输出给定年份,月份的日历 * * @author ywf * */ public class CalenderTest { // 1900年1月1日是星期一 private final int start = 1900; private final int week_start = 1; /** * 输出月份对应的英文标识 * * @param n * @return */ public String getMonthName(int n) { String str = ""; switch (n) { case 1: str = "January"; break; case 2: str = "February"; break; case 3: str = "March"; break; case 4: str = "Aprial"; break; case 5: str = "May"; break; case 6: str = "June"; break; case 7: str = "July"; break; case 8: str = "August"; break; case 9: str = "September"; break; case 10: str = "October"; break; case 11: str = "November"; break; case 12: str = "March"; break; default: str = "输入月份不合理,请重新输入"; } return str; } /** * 得到year年第month月的天数 * * @param year * @param month * @return */ public int getDays(int year, int month) { 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 (isRunyear(year)) { days = 29; } else { days = 28; } break; } return days; } /** * 判断year年是否是闰年 * * @param year * @return */ private boolean isRunyear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { return true; } else { return false; } } /** * 得到从1900年1月1日到year年month月1日的总天数 * * @param year * @param month * @return */ public int getweekStart(int year, int month) { int daysall = 0; for (int i = start; i < year; i++) { if (isRunyear(i)) { daysall += 366; } else { daysall += 365; } } for (int i = 1; i < month; i++) { daysall += getDays(year, i); } return (daysall + week_start) % 7; } /** * 打印日历标题 * * @param year * @param month */ public static void printCalenderTitle(String year, String month) { System.out.println(" " + year + " " + month + " "); String str = "Sun\tMon\tTue\tWed\tThu\tFri\tSat"; for (int i = 0; i < str.length(); i++) { System.out.print("_"); } System.out.println(); System.out.println("Sun\tMon\tTue\tWed\tThu\tFri\tSat"); } /** * 打印月份体 * * @param year * @param month */ public void printMonthBody(int year, int month) { int weekStart = getweekStart(year, month);// month月第一天的星期 int days = getDays(year, month);// month月的天数 int num = 0; for (int i = 0; i < weekStart; i++) { System.out.print("\t"); num++; } for (int i = 0; i < days; i++) { if ((i + num) % 7 == 0) { System.out.println(); } System.out.print(i + 1 + "\t"); } } public static void main(String[] args) { CalenderTest test = new CalenderTest(); Scanner input = new Scanner(System.in); System.out.print("Enter full year (e.g.,2001) :"); int year = input.nextInt(); System.out.print("\nEnter month in number between 1 and 12 :"); int month = input.nextInt(); String yearString = String.valueOf(year); String monthString = test.getMonthName(month); test.printCalenderTitle(yearString, monthString); test.printMonthBody(year, month); } }