概述:
递归:指在当前方法内调用自己的这种现象。
递归的分类:递归分为两种,直接递归和间接递归。
直接递归称为方法自身调用自己。
间接递归可以A方法调用B方法,B方法调用C方法,C方法调用A方法。
注意事项:
1.递归一定要有条件限定,保证递归能够停止下来,否则会发生栈内存溢出。
2.在递归中虽然有限定条件,但是递归次数不能太多。否则也会发生栈内存溢出。
3.构造方法,禁止递归。
递归的使用前提:
当调用方法的时候,方法的主体不变,每次调用你发给发的参数不同,可以使用递归。
public static void main(String[] args) {
a();
}
private static void a() {
a(); // 直接递归,无限调用,栈溢出异常!
}
解释占内存溢出异常原因:
main方法压栈执行,调用a方法,继续压栈,。。。

举例:
1.斐波那契数列
/*
斐波那契数列
F(0)=0,F(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2,n ∈ N*)
*/
public class Demo13Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个数:");
int n = sc.nextInt();
if(n < 0){
System.out.println("输入异常!");
}else {
System.out.println("结果为:" + a(n));
}
}
private static int a(int n) {
if(n == 0 || n == 1){
return n;
}else{
return a(n - 1) + a(n - 2);
}
}
}
2.递归累加求和
/*
计算1~n的和
*/
public class Demo13Sum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入需要的数:(输入为空则停止)");
while(sc.hasNext()){ // 循环键入
int n = sc.nextInt();
// if
System.out.println("累加和为:" + sum(n));
}
}
private static int sum(int n) {
if(n == 1){ // 递归的结束条件
return 1;
}else{
return sum(n - 1) + n;
}
}
}
如果仅仅是计算1-n之间的和,不推荐使用递归,会导致内存中有多个sum方法,效率低下,使用for循环即可。
3.递归求阶乘
public class Demo13Multiply {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入需要的数:");
while(sc.hasNext()){ // 循环键入
int n = sc.nextInt();
System.out.println("累乘积为:" + sum(n));
}
}
private static int sum(int n) {
if(n == 1){ // 递归的结束条件
return 1;
}else{
return sum(n - 1) * n;
}
}
}
4.打印多级目录
/*
练习:递归打印多级目录
需求:遍历D:\\a文件及,及a文件夹下的子文件夹
D:\\a
D:\\a\\a.txt
D:\\a\\aa.txt
D:\\a\\b
D:\\a\\b\\b.txt
D:\\a\\b\\bb.txt
D:\\a\\c
D:\\a\\c\\c.txt
D:\\a\\c\\cc.txt
*/
public class Demo13Recurison2 {
public static void main(String[] args) {
File dir = new File("D:\\a");
getAllFile(dir);
}
/*
定义一个方法,参数传递File类型的目录
*/
public static void getAllFile(File dir){
File[] files = dir.listFiles();
for (File file : files) {
System.out.println(file);
if(file.isDirectory()){
getAllFile(file);
}
}
}
}
打印截图:

1823

被折叠的 条评论
为什么被折叠?



