递归
定义:
A方法调用A方法
(就是自己调用自己)
举例(1):
package com.liu.method;
public class Demo06 {
public static void main(String[] args) {
// 会报 栈溢出异常
Demo06 demo06 = new Demo06();
demo06.test();
}
public static void test(){
test();
}
}
举例(2)
package com.liu.method;
public class Demo07 {
/*阶乘:
2! = 2*1
3! = 3*2*1
4! = 4*3*2*1
*/
//递归(栈机制)
//能不用递归就不用递归,非要使用的话,前提是量比较小
public static void main(String[] args) {
System.out.println(f(1));
}
public static int f(int n){
if (n==1){
return 1;
} else {
return n*f(n-1);
}
}
}
递归思想的图文理解:
(图文以举例2为例题)