查找递归调用的最后一个实例

时间:2018-11-02 16:24:21

标签: java recursion

我具有以下递归步骤来删除目录:

public static boolean deleteDB(File directoryToBeDeleted) {
    File[] allContents = directoryToBeDeleted.listFiles();
    if (allContents != null) {
        for (File file : allContents) {
            deleteDB(file);
        }
    }
    System.out.println("DB deleted");
    return directoryToBeDeleted.delete();
}

现在,每次删除文件或文件夹时,我的打印语句都会打印出来。我如何捕捉上一次删除的时间?

3 个答案:

答案 0 :(得分:3)

对于第一次调用的通过标志为true,在递归方法内部为false。用if(flag)包裹System.out

答案 1 :(得分:1)

艾哈尔所说的差不多。这是一个将整数向下计数的示例。它远非优美,但可能有助于说明问题:

public class RecursiveTracker {

    public static void main(String[] args) {
        deleteSomething(12);
    }

    public static boolean deleteSomething(int counter) {
        if(counter == 0) { 
            return false;
        }
        if(!deleteSomething(--counter) ) { 
            System.out.println("last " + counter);
        } else { 
            System.err.println("This i would not print " + counter);
        }
        return true;
    }

}

这将打印:

last 0
This i would not print 1
This i would not print 2
This i would not print 3
This i would not print 4
This i would not print 5
This i would not print 6
This i would not print 7
This i would not print 8
This i would not print 9
This i would not print 10
This i would not print 11

我认为您的情况是检查是否有更多文件要删除,或者directoryToBeDeleted.listFiles();不返回更多文件

答案 2 :(得分:1)

您可以按级别跟踪递归函数。试试这个:

public static boolean deleteDB(File directoryToBeDeleted, int level = 0) {
    File[] allContents = directoryToBeDeleted.listFiles();
    if (allContents != null) {
        for (File file : allContents) {
            deleteDB(file, level+1);
        }
    }
    if(level == 0)
    {
        System.out.println("DB deleted");
    }
    return directoryToBeDeleted.delete();
}