2015-12-30 95 views
3

我创建了一个按名称查找jcomponents的递归方法。此方法找到正确的组件,但它返回null。我猜我没有正确处理组件的返回和返回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; 
} 

这将立即停止。有一个Component没有Components所以我猜它会立即停止并返回null?

,如果我从findComponent(str, c);删除return控制台提供了:

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 

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

+0

你'for'循环应该只有'tt'是'instanceOf'容器启动。 – LIProf

+0

那么我将如何迭代所有的tt组件呢? – PushALU

+0

在循环之前需要if语句。 (类似于'if(tt instanceOf Container){// start loop';在'else'部分中检查名称是否匹配并返回组件或null。 – LIProf

回答

4

else块应该是:

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

否则,你就只能检查你的第一个组成部分,只有其第一次要和仅是第一子子组件等。

+0

感谢spot on!:) – PushALU

4

你的else块需要return你递归的。喜欢的东西,

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

在你else块,你还需要一个return声明:

return findComponent(str, c);

0

这是因为你在最后返回null ..删除了这一行,并更改循环返回递归调用..在其他..

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

把你的return null;声明在你的[R else块的代码,像这些:

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

扩大我对你的问题的评论,我会尝试这样的事:

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; 
}