递归:return似乎没有退出函数

时间:2015-12-07 15:14:08

标签: file search recursion return

我完全被这个问题困住了。我的函数看起来好像它返回一个值,但一直运行,直到它返回函数底部的值,这是我的逻辑是一段无法访问的代码。我相信我对递归的理解中缺少一些东西。

“System.out.println”方法已经放在返回之前,我尝试调试代码并将其保留,以便您可以看到代码“去”的位置。

我正在尝试在目录(及其所有子目录)中搜索句子中包含的文件名。

我用我的主要方法称呼它:

    System.out.println(findFile(knowledge, "hello i am tom" ));

文件“knowledge”是一个包含两个目录的目录:“people”和“词汇”,“people”不包含任何文件。 “词汇表”包含目录“问候”,其中包含文件“hello”。

这是函数

public static String findFile(File directory, String sentence){
    File[] list = directory.listFiles();
    if (list != null){
        for (File fil : list){
            if (sentence.toLowerCase().contains(fil.getName())){
                System.out.println("found a match: " + fil.getName());
                return fil.getAbsolutePath();
            }
            else if (fil.isDirectory()){
                System.out.println("recur, " + fil + " is empty");
                findFile(fil, sentence);
            }
        }
    }
    else if (list == null){
        return "the list was null";
    }
    System.out.println("this piece of code should be unreachable right?")
    return "the list was neither null nor not null";
}`

这是输出

recur, knowledge/people is empty
this should be unreachable, right?
recur, knowledge/vocabulary is empty
recur, knowledge/vocabulary/greeting is empty
found a match: hello
this should be unreachable, right?
this should be unreachable, right?
the list was neither null nor not null

最后一行是从main.out.println中的main方法打印返回的函数。 请帮忙!

(注意:这不是家庭作业或工作,我只是回到编码,因为我的房东不允许宠物,所以我正在建立AI作为一个良好的第一个项目回来)

1 个答案:

答案 0 :(得分:0)

        else if (fil.isDirectory()){
            System.out.println("recur, " + fil + " is empty");
            findFile(fil, sentence);
        }

在这里你应该改成return findFile(fil, sentence);以将内部函数调用的结果返回给调用者。

相关问题