3

我对 Java 很陌生,并试图弄清楚如何将下面的代码转换为 for 循环或 for each 循环。

do {
    testPages.push(testParentPage);
    if(homePage != null && testParentPage.getPath().equals(homePage.getPath())){
        isParent = true;
        break;
    }
} while((testParentPage = testParentPage.getParent()) != null); 

任何帮助是极大的赞赏!谢谢!

4

4 回答 4

5

它可以在 for 循环中重写,如下所示:

for (; testParentPage != null; testParentPage = testParentPage.getParent()) {
    testPages.push(testParentPage);
    if(homePage != null && testParentPage.getPath().equals(homePage.getPath())){
        isParent = true;
        break;
    }
}

我想我必须承认我不知道它是否有任何好处。

于 2013-04-08T20:51:29.067 回答
4

尝试

for(; testParentPage != null; testParentpage = testParentPage.getParent()) {
    ...
}

for循环结构是(变量初始化;布尔测试;赋值)——通常变量是整数,测试是<或>,赋值是增量,但不一定是这样。

于 2013-04-08T20:51:37.750 回答
0

实际上,do .. while在这种情况下,循环看起来非常合适。如果你有一个“正常”的集合或给你一个迭代器的东西,一个forforeach循环将是选择的工具。但在这种情况下(向上导航树结构)使用for循环恕我直言实际上会令人困惑。

除此之外,for循环的条件总是在执行循环体之前进行评估。由于您需要至少执行一次主体,这会使事情变得更加困难和/或复杂。

编辑:当然,在循环开始时执行空值检查实际上可能是有意义的,因为您testParentPage在循环体中调用了一个方法。

于 2013-04-08T20:52:26.383 回答
0

回复:for-each 循环。

for each 循环遍历 Collection 或数组(请参阅文档),因此您将无法(立即)将您的 do-while 循环转换为 for-each 循环,因为您正在遍历自定义的层次结构。

如果您有一个List<TestPageParent>(或任何类型的名称),它将起作用。也会TestPageParent[]。或Collection<TestPageParent>

于 2013-04-08T20:52:49.693 回答