| |
The break Statement Variations | page 5 of 9 |
Java provides a break command that forces an immediate end to a control structure (while , for , do , and switch ).
The same problem of keeping a running total of integers provides an example of using the break statement:
ConsoleIO console = new ConsoleIO();
total = 0;
number = 1; /* set to an arbitrary value */
while (number >= 0)
{
System.out.print( "Enter a number (-1 to quit) --> ");
number = console.getInt();
if (number < 0)
break;
total += number; // this does not get executed if number < 0
}
- As long as
(number >= 0) , the break statement will not occur and number is added to total .
- When a negative number is typed in, the
break statement will cause program control to immediately exit the while loop.
The keyword break causes program control to exit out of a while loop. This contradicts the rule of structured programming that states that a control structure should have only one entrance and one exit point.
The switch structure (to be covered in a later lesson) will require the use of the break statement.
|