java打印日历
提示输入年份和月份,然后打印出该月的日历,代码如下:
import java.util.*;
public class Chapter5_34 {
//Main method
public static void main(String[] args){
Scanner input = new Scanner(System.in);
//prompt the user to enter year
System.out.print("Enter full year (e.g.,2001):");
int year = input.nextInt();
//prompt the user to enter month
System.out.print("Enter month in number between 1 and 12:");
int month = input.nextInt();
printMonth(year,month);
}
public static void printMonth(int year , int month){
//print the headings of the calendar
printMonthTitle(year , month);
//print the body of the calendar
printMonthBody(year , month);
}
/**print the month title,e.g.,may , 1999*/
public static void printMonthTitle(int year , int month){
System.out.println(" " + getMonthName(month) + " " + year);
System.out.println(" ---------------------------");
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
}
/**
* Get the English name for the month
*/
public static String getMonthName(int month){
String monthName = " ";
switch (month) {
case 1 : monthName = "January";break;
case 2 : monthName = "February";break;
case 3 : monthName = "March";break;
case 4 : monthName = "April";break;
case 5 : monthName = "May";break;
case 6 : monthName = "June";break;
case 7 : monthName = "July";break;
case 8 : monthName = "August";break;
case 9 : monthName = "September";break;
case 10 : monthName = "October";break;
case 11 : monthName = "November";break;
case 12 : monthName = "December";break;
}
return monthName;
}
/**
* Print month body
*/
public static void printMonthBody(int year , int month){
//Get start day of the week fot the first date in the month
int startDay = getStartDay(year , month);
//Ger number of days in the month
int numberOfDaysInMonth = getNumberOfDaysInMonth(year , month);
//Pad space before the first day of the month
int i = 0;
for(i = 0;i < startDay;i++){
System.out.print("");
for(i = 1;i <=numberOfDaysInMonth;i++){
System.out.printf("%4d", i);
if((i + startDay)%7 == 0)
System.out.println();
}
System.out.println();
}
}
public static int getStartDay(int year ,int month){
int j , k , h;
j = year / 100;
k = year % 100;
h = (1 + (26*(month + 1)/10) + k + (k/4) + (j/4) + 5*j)%7;
return h+7;