Next: break statement. Up: Booleans and breaks. Previous: None.


Using the boolean type

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.

boolean has_guessed = false;
while(!has_guessed) {
    IO.println("Guess a number. ");
    if(IO.readInt() == 32) has_guessed = true;
}
IO.println("You got it!");
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.

It's tempting to write something like the following.

while(has_guessed == false) { //...
This has the same effect as while(!has_guessed), but the style is worse - it's wordier, and it doesn't read as nicely.

Notice that we could have avoided the if statement in our loop.

while(!has_guessed) {
    IO.println("Guess a number. ");
    has_guessed = (IO.readInt() == 32);
}
This works because the != operator computes a boolean, which we can simply place into the has_guessed flag.


Next: break statement. Up: Booleans and breaks. Previous: None.