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!"