Thinking in Java

Chapter 4 Controlling Execution

2018-10-06  本文已影响0人  綿綿_

Foreach syntax

for(float x : f) 
System.out.println(x);

This defines a variable x of type float and sequentially assigns each element of f to x.

Break and continue

Break quits the loop without executing the rest of the statements in the loop. Normally, you’d use a break like this only if you didn’t know when the terminating condition was going to occur.

Continue stops the execution of the current iteration and goes back to the beginning of the loop to begin the next iteration.

The infamous “goto”

Lable

A label is an identifier followed by a colon, like this:

label1:

The only place a label is useful in Java is right before an iteration statement. And that means
right before—it does no good to put any other statement between the label and the iteration.

The example using lable:

label1: outer-iteration { 
inner-iteration { //...
break; // (1) //...
continue; // (2) //...
continue label1; // (3) //...
break label1; // (4) } }

In (1), the break breaks out of the inner iteration and you end up in the outer iteration.
In (2), the continue moves back to the beginning of the inner iteration.
But in (3), the continue label1 breaks out of the inner iteration and the outer iteration, all the way back to label1. Then it does in fact continue the iteration, but starting at the outer iteration.
In (4), the break label1 also breaks all the way out to label1, but it does not reenter the iteration.
It actually does break out of both iterations.

Switch

The switch is a selection statement. The switch statement selects from among pieces of code based on the value of an integral expression.
Its general form is:

switch(integral-selector) {
case integral-value1 : statement; break; 
case integral-value2 : statement; break; 
case integral-value3 : statement; break; 
case integral-value4 : statement; break; 
case integral-value5 : statement; break; 
// ...
default: statement;
}

In the preceding definition that each case ends with a break, is the conventional way to build a switch statement, but the break is optional. If it is missing, the code for the following case statements executes until a break is encountered. The last statement, following the default, you could put a break after there or not based on your code style.

The switch statement requires a selector that evaluates to an integral value, such as int or char. If you want to use, for example, a string or a floating point number as a selector, it won’t work in a switch statement.
For non-integral types, you must use a series of if statements.

上一篇下一篇

猜你喜欢

热点阅读