Search code examples
javasling

do while loop to for each or for loop


I'm pretty new to Java and trying to figure out how I would convert the below code to a for loop or a for each loop.

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

Any help is greatly appreciated! Thanks!


Solution

  • It can be rewritten in a for loop like this:

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

    Thought I must admit that I don't know if it serves any benefit.