Next: break statement. Up: Booleans and breaks. Previous: None.
Textbook: Section 4.5
The boolean type is a bit odd. We use it quite a bit when we're programming, but it's not often that you think about it. For example, the expression i < n computes a boolean value. But generally we just put these expressions to compute a boolean value as the condition to an if or a while statement.
But sometimes it's useful to have a variable that holds a boolean value. Such a variable is generally called a flag. For example, quite often you might use a flag to indicate when it's time to stop running through a loop.
In this example, we repeatedly ask the user to guess a number, until at last the user guesses 32. When the user guesses 32, the computer sets the has_guessed flag to true, which prevents the program from going through the loop again.boolean has_guessed = false; while(!has_guessed) { IO.println("Guess a number. "); if(IO.readInt() == 32) has_guessed = true; } IO.println("You got it!");
It's tempting to write something like the following.
This has the same effect as while(!has_guessed), but the style is worse - it's wordier, and it doesn't read as nicely.while(has_guessed == false) { //...
Notice that we could have avoided the if statement in our loop.
This works because the != operator computes a boolean, which we can simply place into the has_guessed flag.while(!has_guessed) { IO.println("Guess a number. "); has_guessed = (IO.readInt() == 32); }
Next: break statement. Up: Booleans and breaks. Previous: None.