Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return statement not working

Tags:

java

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;
}
like image 201
user1688404 Avatar asked May 28 '26 23:05

user1688404


2 Answers

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.

like image 50
BobTheBuilder Avatar answered May 30 '26 12:05

BobTheBuilder


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.

like image 23
Karthik T Avatar answered May 30 '26 13:05

Karthik T