简体   繁体   中英

Return statement in a recursive Java method not terminating method

I am new to recursion in Java and working on a class for searching for a file and returning the location of the file in question.

I ran into one small issue. When the desired file is found, then the method is supposed to return the String of the file location within the "else if" block and terminate the method. Instead, the default String ("File Not Found") is returned instead, only used for when the desired file is not found.

I do know that the function can detect the desired file, I made a print statement (commented out) within the 'else if' block printing out the file location and that works, but again, returning a value in the "else if" block does not terminate the method and just runs its 'default' return value.

Any ideas or suggestions?

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"));
    }

}

The problem is that you ignore the value returned by the recursive call findFile(list[i], target) . When that call finds the target file, you should return the value it returns.

Change:

        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;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM