递归Java方法中的返回语句未终止方法



我是Java中的递归的新手,并在课程中搜索文件并返回所讨论的文件位置。

我遇到了一个小问题。当找到所需的文件时,该方法应该返回" else if"块中的文件位置的字符串并终止方法。而是返回默认字符串("未找到"(,仅在找不到所需文件时才用于。

我确实知道该函数可以检测所需的文件,我在" else if"块中进行了一个打印语句(注释(,在" else"块中打印出文件位置并有效,但是再次,在" else"中返回一个值如果"块没有终止方法,而只是运行其'默认'返回值。

有什么想法或建议?

import java.io.File;
import java.util.*;
public class FileSearch {
    public static String findFile(File path, String target) {
        if (path == null || !path.exists()) {
            return ("Path Doesnt Exist."); // If no such path exists.
        }
        File[] list = path.listFiles();
        if (list != null) {
            for (int i = 0; i < list.length; i++) {
                // Calls if another directory is found.
                if (list[i].isDirectory()) {
                    // System.out.println("Searching Path...");
                    findFile(list[i], target);
                }
                // Block for when desired file is located.
                else if (target.equals(list[i].getName())) {
                  //System.out.println(list[i].getPath());
                    return (list[i].getPath()); // Desired return value, supposed to terminate method and pass value to main.
                }
            }
        }
        return "File Not Found"; // Message if file is not found.
    }
    // Main method to test out return value of method
    public static void main(String[] args) {
        System.out.println(findFile(new File("C:\Users\"), "file.exe"));
    }
}

问题是您忽略了递归调用findFile(list[i], target)返回的值。当该调用找到目标文件时,您应该返回其返回的值。

更改:

        if (list[i].isDirectory()) {
            // System.out.println("Searching Path...");
            findFile(list[i], target);
        }

to:

        if (list[i].isDirectory()) {
            // System.out.println("Searching Path...");
            String result = findFile(list[i], target);
            if (!result.equals("File Not Found") && !result.equals("Path Doesnt Exist.")) {
                return result;
            }
        }

最新更新