在递归方法内的循环中添加计数器 - Java [英] Adding counter to a loop inside a recursive method - Java

查看:1424
本文介绍了在递归方法内的循环中添加计数器 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,它遍历提供的目录数组并打印出那里的所有音频文件。我想添加一个计数器来获取总扫描中找到的所有音频文件。目前,每当

I have a method which iterates over a supplied array of directories and prints out all of the audio files in there. I want to add a counter to get a total of all audio files found from the total scan. At the moment, whenever the

if(file.isDirectory()){new MusicGetter(path).lookup();}

满足条件并移动到新文件夹,总计重置。

condition is met and it moves onto a new folder, the total is reset.

感谢您的帮助:)

完整方法:

public void lookup()
{     
    File folder = new File(c);       
    //File[] listOfFiles = folder.listFiles();
    int count = 0;

    if(folder.listFiles() == null)
    {            
        return;            
    }

    for (File file : folder.listFiles())
    {
        String path = file.getPath();

        //in each directory print out the audio files
        if(path.contains(".mp3") || path.contains(".wav") || path.contains(".flac") || path.contains(".m4a") || path.contains(".ogg") || path.contains(".wma"))
        {
            System.out.println(path);   
            count++;                             
        }            

        //call method again if the file is a directory
        if (file.isDirectory())
        {
            new MusicGetter(path).lookup();               
        }           
    }        
    System.out.println("count is" + count);        
}


推荐答案

我会改变方法 void 返回类型 int 并按如下方式执行:

I would change the method from void to return type int and do it as follows:

 public int lookup()
    {     
        File folder = new File(c);       
        //File[] listOfFiles = folder.listFiles();
        int count = 0;

        if(folder.listFiles() == null)
        {            
            return count;            
        }

        for (File file : folder.listFiles())
        {
            String path = file.getPath();

            //in each directory print out the audio files
            if(path.contains(".mp3") || path.contains(".wav") || path.contains(".flac") || path.contains(".m4a") || path.contains(".ogg") || path.contains(".wma"))
            {
                System.out.println(path);   
                count++;                             
            }            

            //call method again if the file is a directory
            if (file.isDirectory())
            {
                count += new MusicGetter(path).lookup();               
            }           
        }
        return count;     
        System.out.println("count is" + count);        
    }

这篇关于在递归方法内的循环中添加计数器 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆