簡體   English   中英

以遞歸方式查找對象,找到后返回null

[英]Finding an object recursively, returns null when found

我已經創建了一個通過名稱查找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;
}

這將立即停止。 有一個Component沒有Components所以我猜它會立即停止並返回null?

如果我從findComponent(str, c);刪除return 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

title是不包含任何組件的title。 這是一個新問題嗎?

你的else塊需要return你遞歸的內容。 就像是,

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

你的else塊應該是:

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

否則,您將只檢查您的第一個組件,只檢查其第一個子組件,並且只檢查第一個子組件,依此類推。

在你的else塊中,你還需要一個return語句:

return findComponent(str, c);

這是因為你在最后返回null ..刪除該行並更改該循環以返回遞歸調用..在else ..

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

把你的return null; 你的else代碼塊中的語句,如下所示:

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

擴展我對你的問題的評論,我會嘗試這樣的事情:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM