赞
踩
14.10(显示日历)改写程序清单5-12中的PrintCalendar类,使用Calendar类和GregorianCalendar类显示指定月份的日历。
一开始写的时候有点没有思绪,因为Calendar类看的不是很仔细,有些功能都不知道要怎么实现,重新翻了两遍才找到了要用的方法:
第一个是Calendar.get(Calendar.DAY_OF_WEEK)用来找出本月1号是星期几
第二个是Calendar.getActualMaximum(Calendar.DAY_OF_MONTH)用来找出本月有多少天
一开始因为不知道这两个方法,甚至还想用getTimeInMillis()得到毫秒数,然后再用第五章的老方法一点点算出来,后来实在是懒,于是去翻书找有没有直接可以用的方法,还好找到了,感觉虽然看了遍书,但是对很多类中的方法一点都不熟练,sigh
import java.util.*;
public class Exercise14_10 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int month = input.nextInt();
int year = input.nextInt();
int day = 1;
Calendar c = new GregorianCalendar(year,month-1,day);
int firstDay = c.get(Calendar.DAY_OF_WEEK);
int dayOfMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
printMonthTitle(year,month);
printMonthBody(year,month, firstDay, dayOfMonth);
input.close();
}
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 ");
}
public static String getMonthName(int month) {
String monthName = " ";
switch(month) {
case 1: monthName = "January"; break;
case 2: monthName = "Febuary"; 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";
}
return monthName;
}
public static void printMonthBody(int year, int month, int startDay, int dayOfMonth) {
for(int i = 1; i< startDay;i++) {
System.out.print(" ");
}
for(int i = 1;i <= dayOfMonth; i++) {
if((i + startDay-2) % 7 ==0)
System.out.println();
if(i <10 ) {
System.out.print(" ");
}
System.out.print(" "+ i );
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。