Home > database >  Use counter to keep track from a function to global level
Use counter to keep track from a function to global level

Time:11-11

    public static void main(String args[]){
        extract("e:\\");
    }
    public static void extract(String p){
        File f=new File(p);
        File l[]=f.listFiles();
        int counter = 0;
        for(File x:l){
            if(x.isDirectory()) extract(x.getPath());
            else if(x.getName().endsWith(".mp3"))){
                counter = counter   1;
            }
        }
// I want to count and return value at last
    }

Using this method(above), resets the counter every time when for loop ends. So here, I want to count even when the for loop ends so that I can keep track of the number of .mp3 files.

I want to count and return value at last.

CodePudding user response:

You should not use recursion like that. (Recursion should always have a termination condition to avoid running in a loop forever! I think the problem is, that you create new Integers every time you call your method, so you will eventually override your old value or even use many different Integers to count. You can wrap everything in a class in which you keep track of one integer.

Some pseudo-code:

public class Mp3Counter {
    
    private int numberOfMp3 = 0;
    
    public void extract(...) {
        if (foundMp3) {
            this.numberOfMp3  = 1;    
        }
    }
}

CodePudding user response:

Return the current counter and make sure you add the response when you call recursively back to the counter.

public static void main(String args[]) {
  int count = extract("../");
}

public static int extract(String p) {
  File f = new File(p);
  File l[] = f.listFiles();
  int counter = 0;
  for (File x : l) {
    if (x.isDirectory()) {
      counter  = extract(x.getPath());
    } else if (x.getName().endsWith(".mp3")) {
      counter  ;
    }
  }
  return counter;
}
  • Related