1

I'm trying to find the a parent Directory only given its name, i.e. I have a Directory name and I need to find it and return it.
I used ArrayList to represent Directory. In addition, I don't know what's the depth of the Directory I'm looking for so I used recursion, I only know the Directory exists and I need to return it.

My code is:

private static Directory getParentDirectory(String parentDirName, Directory currentDirectory, int level) {

    if (currentDirectory.getName().equals(parentDirName)) {
        return currentDirectory;

    } else {
        // Recursively search for the parent Directory
        for (Entity item : currentDirectory.contents) {
            if (item instanceof Directory) {
                getParentDirectory(parentDirName, (Directory) item, level + 1);
            }
        }
    }
    System.out.println("Couldn't find relevant Directory!");
    return currentDirectory;
}

My problem is with the recursion- I don't know why but even if first "if" statement is met (and Dir was found), the function still continues with the recursion doesn't exit when return and prints "Couldn't find relevant Directory!"

1 Answer 1

3

Instead of return default value, you can just return during recursive call if found.

private static Directory getParentDirectory(String parentDirName, Directory currentDirectory, int level) {

    if (currentDirectory.getName().equals(parentDirName)) {
        return currentDirectory;

    } else {
        // Recursively search for the parent Directory
        for (Entity item : currentDirectory.contents) {
            if (item instanceof Directory) {
                Directotry result = getParentDirectory(parentDirName, (Directory) item, level + 1);
                if (result != null) {
                    return result;
                }
            }
        }
    }
    return null;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.