迷惑人的递归问题

  最近研究tire树的时候,写了个demo,涉及到递归 ,发现老是不能得到自己想要的结果,仔细分析house才发现原来被迷惑了。

  代码如下:

public static boolean tests(int  i){
        if(i>5){
            return false;
        }
        if(true){
            tests(++i);
        }
        return true;
    }

  最终发现只要i<6,返回的都是true,这不符合我想要的结果,应该不管传几double应该是false;

  分析如下:因为方法递归调用中tests(++i)方法是没有返回值的,所以第一次调用的参数值会继续往下执行,所以会一直为true。所以women在递归调用的时候最好要有返回值。

  正确代码如下:

public static boolean tests(int  i){
        if(i>5){
            return false;
        }
        if(true){
           return tests(++i);
        }
        return true;
    }
或者

public static boolean tests(int  i){
        boolean flag = false;
        if(i>5){
            return false;
        }
        if(true){
          flag =  tests(++i);
        }
        return flag;
    }

  

posted @ 2016-09-16 00:21  骚客的风  阅读(148)  评论(0编辑  收藏  举报