I'm trying out the guessing game example in Ch. 2 of Head First Java. I've copied it and saved it (I like to do this, maybe to help get a feel for what's going on). I've saved it all on one file called GuessGame: Here's the code :
This is the entire program -- I have them saved as separate classes, so it compiled and ran fine. What I'd like to know is what does the while (true) condition mean in line 22? I know it has something to do with the booleans, but I'm not sure how to interpret the statement. What is going on that causes it to execute the statement inside the while loop?
Christopher Laurenzano wrote: What I'd like to know is what does the while (true) condition mean in line 22?
Normally when you have a loop, you write a condition inside the parens that evaluates to true or false which Java uses to determine whether to execute the loop another time. This example, always evaluates to true so Java always goes on to another loop execution.
The "break" in the loop is so this doesn't go on forever. When "break" is encountered, Java continues execution after the loop.
I meant to ask what does true refer to, or what condition is being evaluated that is either true or false? Is it evaluating the values of the p1isRight - p3isRight variables? or is it something else, because there are no other boolean variables/values in the file.
author & internet detective
Actually these sort of things are mostly used in threads. If you want a thread to look at or get a value endlessly. While always requires a boolean value. SO inside a while, all expressions should evaluate to a boolean i.e in other words expressions are references to a boolean value in a loop. This may not sound good but its just hypothetical. So while(true) is a way of telling, run as much as you want like a never ending loop. Only way to get out of the loop is break, return and System.exit().
[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api