2015-12-30 29 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; 
}