1 public class Recursion01{ 2 public static void main(String[] args){ 3 T t1 = new T(); 4 t1.test(4);//輸出什麼? n=2 n=3 n=4 5 int res = t1.factorial(5); 6 System.out.println("5 的階乘 res =" + res); 7 8 9 } 10 } 11 12 class T{ 13 //分析 14 public void test(int n){ 15 if(n > 2){ 16 test(n-1); 17 } 18 System.out.println("n =" + n); 19 } 20 //factorial 階乘 21 public int factorial(int n){ 22 if(n == 1){ 23 return 1; 24 }else{ 25 return factorial(n-1) * n; 26 } 27 } 28 }