0

I am new to Java so any advice would be really appreciated.
I have a tree-like File System with files and directories. I want to find a Directory by its name. Component is an interface and both File and Directory implement it. I wrote this method in the class Directory in order to find a Directory named name.

public Directory getDir(String name) {
    Iterator<Component> iterator = (Iterator<Component>)components.iterator();
    Component component = null; 
    while(iterator.hasNext()) {
        component = iterator.next();
        if(component instanceof Directory) {
            if(component.getName().equals(name))
                return (Directory) component;
            else component.getDir(name);
         }
     }  
    return null;
}

Somehow, this method won't stop after finding my Directory. I tried writing "return component.getDir(name)" but it doesn't help. It won't search in every component of my node, just in the first one. What am I doing wrong? Please help me. Thank you

0

1 Answer 1

1

Looks like your line: else component.getDir(name) is not checked for a return value. No matter whether that recursive call returns a found directory or null (nothing found), the next thing will be another round in the loop.

Just check whether it returns not null, then return this again.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.