user1688404
user1688404

Reputation: 739

Return statement not working

Can someone help me with fixing my problem. I have a function which checks if a file is present in a particular path. the function checks if the filenames match and also the paths also match.(A file with a particular name could be present in multiple locations). Please find below my code.

memberPath is a static variable which contains the relative path. file_Path is a static variable which gets updated when the match has been found.

My problem is the function finds the match but it breaks out of the for-loop comes to return statement but goes back to the for loop. Can someone help me to fix my code so that once the match is found it returns bac to the calling position.

public static String traverse(String path, String filename) {
        String filePath = null;
        File root = new File(path);
        File[] list = root.listFiles();

        for (File f : list) {
            if (f.isDirectory()) {
                traverse(f.getAbsolutePath(), filename);
            } else if (f.getName().equalsIgnoreCase(filename) && f.getAbsolutePath().endsWith(memberPath)) {
                filePath = f.getAbsolutePath();
                file_Path = filePath;
                break ;
                }
        }
        return filePath;
}

Upvotes: 2

Views: 183

Answers (3)

user1688404
user1688404

Reputation: 739

As pointed by baraky, Karthik and JanDvorak, the updated code is:

public String traverse(String path, String filename) {
        String filePath = null;
        File root = new File(path);
        File[] list = root.listFiles();

        for (File f : list) {
            if (f.isDirectory()) {
                return traverse(f.getAbsolutePath(), filename);
            } else if (f.getName().equalsIgnoreCase(filename)
                    && f.getAbsolutePath().endsWith(memberPath)) {
                filePath = f.getAbsolutePath();
                file_Path = filePath;
                return filePath;

                }
        }       
        return filePath;
    }

Thanks guys!!

Upvotes: 1

Karthik T
Karthik T

Reputation: 31952

The way recursion works is that the function calls itself. So when your function returns, it goes back into the for loop, because it is likely the outer function ( the one that called it) called it from the below line

if (f.isDirectory()) {
            traverse(f.getAbsolutePath(), filename);

Since this is the case, you need to add the return here as baraky explains, else you will lose the answer that the inner function derives.

Upvotes: 3

BobTheBuilder
BobTheBuilder

Reputation: 19284

Add :

return traverse(f.getAbsolutePath(), filename);

to return the value you get by this call.

As pointed out - you can return the value instead of break.

Upvotes: 6

Related Questions