用方法抽象把细节与设计相分离。
自底向下方法是从下向上每次实现结构图中的一个方法。
待完善方法是一个简单但不完善的方法。使用待完善的方法可以快速的构建程序的框架。
对每个实现的方法都写一个测试程序进行测试。
下面粘上打印日历的代码
附上输出结果
package dm13;
import java.util.Scanner;
public class PrintCalender {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner input = new Scanner(System.in);
System.out.print("Enter full year :");
int year = input.nextInt();
System.out.print("Enter month in number between 1 and 12 :");
int month = input.nextInt();
printMonthTitle(year,month);
printMonthBody(year, month);
}
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 = "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;
default: break;
}
return monthname;
}
public static void printMonthBody(int year, int month)
{
int startDay = getStarDay(year, month);
int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);
for(int i = 0; i < startDay; i++)
System.out.print(" ");
for(int i = 1; i <= numberOfDaysInMonth; i++)
{
System.out.printf("%5d", i); //格式化输出
if((i + startDay) % 7 == 0)
System.out.println();
}
System.out.println();
}
public static int getStarDay(int year, int month)
{
return (getTotalNumberOfDays(year, month) + 3) % 7;
}
public static int getTotalNumberOfDays(int year, int month)
{
int total = 0;
for(int i = 1800; i < year; i++)
{
if(isLeapYear(i))
total += 366;
else
total += 365;
}
for(int i = 1; i < month; i++)
{
total += getNumberOfDaysInMonth(year, i);
}
return total;
}
public static int getNumberOfDaysInMonth(int year,int month)
{
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
return 31;
if(month == 4 || month == 6 || month == 9 || month == 11)
return 30;
if(month == 2)
{
if(isLeapYear(year))
return 29;
else
return 28;
}
return 0;
}
public static boolean isLeapYear(int year)
{
return (year % 400 == 0|| (year % 4 == 0 && year % 100 != 0));
}
}
输出结果::
Enter full year :2016
Enter month in number between 1 and 12 :4
April 2016
-----------------------------------
Sun Mon Tue Wed Thu Fri Sat
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
|