Search⌘ K
AI Features

Boolean Variables in Loops

Explore how Boolean variables can control loops in Java, helping you write clear logic for tasks like summing positive numbers and locating characters in strings. Learn loop control with Boolean flags and how to handle loop termination conditions effectively.

The sum of positive numbers

Let’s recall the loop that sums the positive numbers entered by a user, as given earlier in this chapter:

import java.util.Scanner;
public class Example
{
   public static void main(String[] args) 
   {
      Scanner keyboard = new Scanner(System.in);
      
      System.out.println("This program computes the sum of positive numbers you enter as input.");
      System.out.println("A nonpositive number will signal the end of the data.");
 
      double sum = 0;
      System.out.print("Type the next positive number or 0 to end: ");
      double number = keyboard.nextDouble();
      while (number > 0)
      {
         sum = sum + number;
         System.out.print("Type the next positive number or 0 to end: ");
         number = keyboard.nextDouble();
      } // End while
      
      System.out.println("The sum is " + sum);
      System.out.println("All Done!");
	} // End main
} // End Example

The while loop is controlled by the Boolean expression number > 0, whose value is either true or false. We can describe the logic of this loop with the following pseudocode:

sum = 0
while (we are not done)
{
   number = the next number that the user types
   if (number > 0)
      sum = sum + number
   else
      We are done
}

A Boolean variable—like a Boolean expression—has a value that is either true or false, and we can use such a variable to control a loop. So instead of implementing the pseudocode:

while (we are not done)

as:

while (number > 0)

let’s write:

while (!done)

where done is a Boolean variable. We read this as “while not done.” We can initialize done to false. Since !done is true, the loop will execute until done becomes true. ...