Java递归调用

6.递归调用

方法的递归调用就是方法自身调用自身。

以下程序因为递归没有结束的条件,所以一直压栈,没有弹栈,导致栈内存溢出错误!所以递归必须要有结束条件。

public class RecursionTest01{

       //入口

       public static void main(String[] args){

              m1();

       }

       public static void m1(){

              m1(); //java.lang.StackOverflowError

       }

}

【例题1】:不使用递归,计算1-N的求和。

public class RecursionTest02{

       public static void main(String[] args){

              int n = 5;

              //调用该方法完成1-N的求和

              int retValue = method1(n);

              System.out.println(retValue); //15

       }

       //该方法完成1-N的求和.

       public static int method1(int n){

              int sum = 0;

              for(int i=0;i<=n;i++){

                     sum += i;

              }

              return sum;

       }

}

【例题2】:使用递归,计算1-N的求和。

public class RecursionTest03{

       public static void main(String[] args){

              int n = 5;

              //调用该方法完成1-N的求和

              int retValue = method1(n);

              System.out.println(retValue); //15

       }

      

       //该方法完成1-N的求和.

       //1+2+3+4+5+...N

       public static int method1(int n){

              if(n==1){

                     return 1;

              }else{

                     return n + method1(n-1); }}}

【练习】:计算N的阶乘。两种方式:使用递归和不使用递归。

public class RecursionTest04{

       public static void main(String[] rgs){

              System.out.println(method1(5)); //120

       }

       public static int method1(int n){

           //不使用递归

              int result = 1;

              for(int i=1;i<=n;i++){

                     result *= i;

              }

              return result;

           //使用递归

              if(n==1){

                     return 1;

              }else{

                     return n * method1(n-1); }

       }

}

 

 

 

posted @ 2019-11-02 07:20  阿江是个程序猿  阅读(2979)  评论(0编辑  收藏  举报