Java Reference
In-Depth Information
Because the boolean literal true always evaluates to true , this loop appears to
execute indefinitely. But a test occurs in the middle of the loop. This technique is use-
ful for solving fencepost and sentinel problems. For example, Chapter 5 examines a
sentinel problem for summing numbers until
1. This problem can be elegantly
solved with break as follows:
Scanner console = new Scanner(System.in);
int sum = 0;
while (true) {
System.out.print("next integer (-1 to quit)?");
int number = console.nextInt();
if (number == -1) {
break;
}
sum += number;
}
System.out.println("sum = " + sum);
The continue statement immediately ends the current iteration of a loop. The
code execution will return to the loop's header, which will perform the loop's test
again (along with the update step, if it is a for loop). The following loop uses
continue to avoid negative integers:
for (int i = 0; i < 100; i++) {
System.out.print("type a nonnegative integer:");
int number = console.nextInt();
if (number < 0) {
continue; // skip this number
}
sum += number;
...
}
Many programmers discourage use of the break and continue statements
because these statements cause the code execution to jump from one place to another,
which some people find nonintuitive. Any solution that uses break or continue can
be rewritten to work without them.
It is possible to label statements and to break or continue executing from a par-
ticular label. This can be useful for immediately exiting to particular levels from a set
of nested loops. This syntax is outside the scope of this textbook.
The switch Statement
The switch statement is a control structure that is similar to the if/else statement.
It chooses one of many paths (“cases”) to execute on the basis of the value of a given
variable or expression. It uses the following syntax:
 
Search WWH ::




Custom Search