【正文】
h(year, month)。 ? ? // Get number of days in the month ? int numOfDaysInMonth = getNumOfDaysInMonth(year, month)。 ? ? // Print body ? printMonthBody(startDay, numOfDaysInMonth)。 ? long totalNumOfDays = getTotalNumOfDays(year, month)。 ? } ? 例 ? // Get the total number of days since Jan 1, 1800 ? static long getTotalNumOfDays(int year, int month) ? { ? long total = 0。 i year。 ? else ? total = total + 365。 i month。 ? ? return total。 ? ? if (month == 4 || month == 6 || month == 9 || month == 11) ? return 30。 ? else ? return 28。 // If month is incorrect. ? } 例 ? // Determine if it is a leap year ? static boolean isLeapYear(int year) ? { ? if ((year % 400 == 0) || ((year % 4 == 0) amp。 (year % 100 != 0))) ? return true。 ? } 例 ? // Print month body ? static void printMonthBody(int startDay, int numOfDaysInMonth) ? { ? // Pad space before the first day of the month ? int i = 0。 i startDay。 ? for (i = 1。 i++) ? { ? if (i 10) ? ( + i)。 ? if ((i + startDay) % 7 == 0) ? ()。 ? } ? 例 ? // Print the month title, . May, 1999 ? static void printMonthTitle(int year, int month) ? { ? ( +getMonthName(month)+, +year)。 ? ( Sun Mon Tue Wed Thu Fri Sat)。 ? switch (month) ? { ? case 1: monthName = January。 ? case 2: monthName = February。 ? case 3: monthName = March。 ? case 4: monthName = April。 ? case 5: monthName = May。 ? case 6: monthName = June。 ? case 7: monthName = July。 ? case 8: monthName = August。 ? case 9: monthName = September。 ? case 10: monthName = October。 ? case 11: monthName = November。 ? case 12: monthName = December。 ? } ? 49 遞歸方法 方法也可以用在遞歸 (recursive),所謂遞歸就是方法本身自己調(diào)用自己。 fac(n)=1*2*L*N,n=1(非遞歸算法) =n*(fac(n1),n=1(遞歸算法) public class ComputeFactorial { public static void main(String[] args) { // Prompt the user to enter an integer (Please enter a nonnegative integer)。 (Factorial of 5 is + factorial(n))。 else return n*factorial(n1)。本例計算fac(4)=4*3*2*1=124,其遞歸計算的過程如圖 所示。 ? int n = ()。 ? } ? public static long fib(long n) ? { ? if ((n==0)||(n==1)) // Stopping condition ? return 1。 ? } ? } 遞歸的缺陷: 當調(diào)用一般方法時,方法里的局部變量會因為方法執(zhí)行完畢而結(jié)束生命周期。 等到開始返回時再由堆棧中取出未完成的部分繼續(xù)執(zhí)行,此時被占用的堆棧才會一一被釋放。