java retain information in recursive function

后端 未结 8 1889
滥情空心
滥情空心 2020-12-29 09:05

Is it possible to retain information via a helper function with java, without using static variables.

For example,

public void foo(){
    int v = 0;
         


        
8条回答
  •  孤城傲影
    2020-12-29 09:44

    Why not make it an instance variable(not necessarily static)...??

    public class Recursive {
        int v = 0;
        public void foo(){
    
            fooHelper(2);
            System.out.println(v);
        }
    
        public void fooHelper(int depth){
            v++;
            if(depth-1!=0)//Added this because I was getting an StackOverflowError
            fooHelper(depth-1);
        }
    
        public static void main(String[] args) {
            Recursive r = new Recursive();
            r.foo();
        }
    }
    

提交回复
热议问题