This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
Akin Millone wrote:please i have a question about a line in chapter 2's guessgame code. The line is line 17: while(true)
I'd like to know... while WHAT is true?
It might be worth adding that the construct should generally be avoided, as it usually involves the loop containing break statements, which are also best kept to a minimum.
It IS sometimes used when all the conditions for ending the loop are difficult to put into a single expression, or when they only become apparent over a series of statements, but it can make path testing quite difficult.
In the context of a game, it's probably used as a substitute for
while(the game isn't over) { ... in which case it may be better to put the body of the loop in a separate method that returns a boolean, and use something like:HIH
Winston
Isn't it funny how there's always time and money enough to do it WRONG?
It's funny how different people develop different prejudices. Personally I hate extraneous flag variables -- the ones introduced just to avoid break statements, for example.
Ernest Friedman-Hill wrote:It's funny how different people develop different prejudices. Personally I hate extraneous flag variables...
Absolutely.
My personal hate is empty loops, but ONLY because Java doesn't have a noop statement, which makes them too easy to miss.
If it did, I'd be with you completely.
chris webster wrote:Just curious, but why is the "for" loop better than a "while" loop like this?
Basically: scope. The 'keepGoing' variable is defined and used exactly where it's needed. Some people may regard it as posteriorly-retentive, but I reckon it's a pretty good rule; which is why I generally prefer for loops to while's.
Winston
Good point - that's what I suspected. I tend to prefer "for" when there is a limit on the number of iterations - either via a count or the no of elements in a collection - and "while" only for an unknown no of iterations (which is much less common anyway). But it's good to learn from my more experienced peers!