Java 递归查找对象,找到时返回null

Java 递归查找对象,找到时返回null,java,recursion,Java,Recursion,我创建了一个按名称查找jcomponents的递归方法。此方法找到正确的组件,但返回null。我猜我没有正确处理组件的返回和返回null。我怎样才能使它正常工作 编辑:更改为,我从下面的评论中理解。但它不会返回组件 public Component findComponent(String str, Component tt){ for (Component c : ((Container) tt).getComponents()) { System.out.pr

我创建了一个按名称查找jcomponents的递归方法。此方法找到正确的组件,但返回
null
。我猜我没有正确处理组件的返回和返回null。我怎样才能使它正常工作

编辑:更改为,我从下面的评论中理解。但它不会返回组件

public Component findComponent(String str, Component tt){   

    for (Component c : ((Container) tt).getComponents()) {
        System.out.println("name: " + c.getName());
        if(c.getName().equals(str)){
            System.out.println("Found it! " + c.getName());
            return c;
        } else {
            return findComponent(str, c);
        }
    }   
    return null;
}
这将立即停止。有一个
组件
没有
组件
,所以我猜它会立即停止并返回null

如果我从
findComponent(str,c)中删除
返回
控制台提供:

name: titel
name: l
name: jpj
name: jtx
name: jpath
Found it! jpath
name: knapper
name: k1
name: n1
name: k2
name: n2
name: k3
name: n3
name: jpp
name: text
name: jpe
name: ta

标题是不包含任何组件的标题。这是一个新问题吗?

您的
else
块需要
返回您递归的内容。大概

} else {
    return findComponent(str, c);
}

else
块中,还需要
return
语句:


返回findComponent(str,c)

这是因为您在最后返回null。。删除该行并更改该循环以返回递归调用。。在另一方面

 if(c.getName() != null){
    if(c.getName().equals(str)){
        System.out.println("Found it! " + c.getName());
        return c;
    } else {
        return findComponent(str, c);
    }
 }

将您的
返回空值else
代码块中的code>语句,如下所示:

} else {
         findComponent(str, c);
         return null;
}

您的
else
块应为:

else {
  Component sub = findComponent(str, c);
  if (sub != null) return sub;
} 

否则,您将只检查第一个组件和它的第一个子组件,并且只检查第一个子组件,依此类推

关于我对你的问题的评论,我想尝试以下方式:

public Component findComponent(String str, Component tt){   
    if ( tt instanceOf Container )
        for (Component c : ((Container) tt).getComponents()) {
            System.out.println("name: " + c.getName());
            if(c.getName().equals(str)){
                System.out.println("Found it! " + c.getName());
                return c;
            } else {
                Component c = findComponent(str, c);
                if ( c != null ) return c;
            }
            return null;
        }
    else if(c.getName().equals(str)){
                System.out.println("Found it! " + c.getName());
                return c;
    }
    else  
        return null;
}

只有当
tt
容器的
实例时,才应启动
for
循环。那么我如何迭代所有tt组件?在循环之前需要if语句。(类似于
if(tt instanceOf Container){//start loop
;在
else
部分中检查名称是否匹配,并返回组件或null。