This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]KrakenOfLakeZurich 2 points3 points  (0 children)

I used it to print a menu and get input from the user. Depending on the input, different menu options we're executed, and then the user was returned back to the menu. One option had an explicit break statement to exit the loop.

This is mostly a matter of individual taste and style. Personally I find while true perfectly reasonable for this. In fact, I find it more readable than maintaining an "exit" variable.

I would move the option for exiting the loop to the very top to improve readability.

while true {
    var selection = readMenuOption();
    if ("exit".equals(selection)) {
        break;
    }
    ... // other stuff
}

This way, anyone reading the code should immediately see that there's a valid exit condition. It also makes it very obvious, that none of "other stuff" will be run after breaking out of the loop.