注意:构造方法不可递归,否则是无限创建对象;
递归的几个经典例子:
1.HannoiTower
import java.util.Scanner; public class HanoiTower{ //level代表盘子个数;三个char类型代表柱子 public static void moveDish(int level, char from, char inter, char to){ if(level == 1){ System.out.println("从"+from+"移动盘子1号到"+to); }else{ moveDish(level-1,from,to,inter);//调用自身 System.out.println("从"+from+"移动盘子"+level+"号到"+to); moveDish(level-1,inter,from,to); } } public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("请输入盘子个数"); int n = sc.nextInt(); moveDish(n,‘a‘,‘b‘,‘c‘); } }
2.sum
import java.util.Scanner; public class Sum{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("请输入n:"); int n = sc.nextInt(); int sum1 = sum(n); System.out.println(sum1; } public static int sum(int n){ if(n == 1){ return 1; }else{ return n+sum(n-1); } } }
3.factorial
import java.util.Scanner; public class Factorial{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("请输入一个小于20的整数,我会帮你求出它的阶乘:"); int n = sc.nextInt(); int fac1 = fac(n); System.out.println(n+"的阶乘为:"+fac1); System.out.println("~看我棒不棒~~"); } public static int fac(int n){ if(n == 1){B return 1; }else{ return n*fac(n-1); } } }
4.sumFactorial
import java.util.Scanner; public class SumFactorial{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("请输入一个小于20的整数:"); int n = sc.nextInt(); int sf = sumFac(n); System.out.println(sf); } //阶乘和的累加 public static int sumFac(int n){ if(n == 1){ return 1; }else{ return fac(n)+sumFac(n-1); } } //求阶乘 public static int fac(int n){ if(n == 1){ return 1; }else{ return n*fac(n-1); } } }
5.使用递归,遍历 1 至100之间的每个数字
public class Number{ public static void main(String[] args){ iterator(100); } public static void iterator(int n){ if(n >= 1){ System.out.print(n+"\t"); n--; iterator(n); } } }
原文地址:http://huguangqin2015.blog.51cto.com/10856722/1940996