[Thinking in Java] Chapter 4th-Controlling the execution process

Source: Internet
Author: User
Tags case statement

4.1 if-else4.2 iterative 4.3 foreach syntax 4.4 return4.5 break and continue4.6 switch
Catalogue 4.1 If-else

The else in If-else is optional, and there are two forms of using if:

if (boolean-expression) statement

Or

if (boolean-expression) statement1 Else Statement2

It is important to note that Boolean-expression cannot be a number, in fact, the conditional expressions in the subsequent while,for cannot be numbers, although we know that C and C + + can use numbers to determine true or false

1 CharTestintscore) {2     if(Score >= 90)3         returnA;4     Else if(Score >= 80)5         returnB;6     Else if(Score >= 70)7         returnC;8     Else if(Score >= 60)9         returnD;Ten     Else //if (Score <) One         returnE;  A}

In the above example, if the comment of line 10th is removed, the compiler will error, although we can understand the designer's intention, but the compiler is not so smart, the compiler will not return a value after the 10th line

4.2 Iterations (while, Do-while, for)

The while, Do-while, and for statements are iterative statements because their statements are executed repeatedly until the Boolean expression that controls them gets the result of "false".

The loop format for while is as follows:

 while (boolean-expression) statement

The Do-while loop format is as follows:

 Do Statement  while (boolean-expression); // do not forget the semicolon;

The only difference between Note:while and Do-while is that the statement in Do-while is executed at least once, even if the expression is evaluated to false for the first time. In the while loop structure, if the condition is false for the first time, the statement is not executed at all.

The format for the For loop is as follows:

 for (initialization; boolean-expression; step) statement

is actually equivalent to the while loop:

initialization  while (boolean-expression) {statement step}

Initialization expressions (initialization), Boolean expressions (Boolean-expression), and stepping operations (step) can all be empty

Comma operator (not comma delimiter)

The only place in Java where the comma operator is used is the control expression for the For loop. In the initialization and step-control sections of the control expression, you can use a series of comma-delimited statements, and those statements run independently

 Public class Commaoperator {    publicstaticvoid  main (string[] args) {           for (int i = 1, j = i + Ten; i < 5; i++, j = i * 2) {            println ("i =" + i + "J =" +  j);     }}} /* i = 1 J = 11i = 2 J = 4i = 3 J = 6i = 4 J = 8 */

The int definition in the FOR statement overrides I and J, and in the initialization part you can actually have any number of variable definitions with the same type. In a control expression, the ability to define multiple variables is limited to the for loop and cannot be used in any other selection statement.

As you can see, statements are executed sequentially, both in the initialization and in the step sections. In addition, the initialization section can have any number of definitions of the same type.

4.3 foreach syntax

foreach is more concise and efficient when accessing arrays and containers, showing examples of accessing arrays

1 int New int [Ten]; 2  for (int i = 1; I <=; i++) 3     A[i-1] = i; 4  for (int  e:a) 5     println (e);

4.4 Return

The return keyword has two purposes: specifying what value a method returns (assuming it is not returning void), on the other hand it causes the current method to exit and returns that value.

Rewrite The example in 4.1 if-else

CharTestintscore) {    if(Score >= 90)        returnA; if(Score >= 80)        returnB; if(Score >= 70)        returnC; if(Score >= 60)        returnD; Else //if (Score <)        returnE; }

This eliminates the need to add else, because the code after return does not continue to execute

A method with a return value of void can also have a return, and if no return is added, the end of the method will have a default implicit return

void Test (int  e) {    if (e = =1        )return;   if E equals 1, the following e++ will not perform the    e++;}

4.5 Break and continue

Break is used to forcibly exit the current loop without performing the remaining iterations, while continue stops executing the current iteration and then returns to the beginning of the loop, continuing the next iteration.

 for(inti = 0; I < 100; i++) {    if(i = = 74) Break;//if equal to 74, exit the Loop    if(i% 9! = 0)Continue;//If it is not an integer multiple of 9, skip the following statement and proceed to the next iterationprintln (i + ""));} println ();inti = 0; while(true) {i++; intj = i * 27; if(j = = 1269) Break;//if J equals 1269, Exit loop    if(i% 10! = 0)Continue;//If I is not an integer multiple of 10, skip the following statement and proceed to the next iterationprintln (i + ""));}

Break and continue can also use tags like the goto keyword, but don't use it a little better. The format is as follows

Label1://tags, note that you must not write any code between Label1 and Outer-iterationouter-iteration {//External iterationsinner-iteration {//Internal iterations// ...         Break;//(1)// ...        Continue;//(2)// ...        ContinueLabel1;//(3)// ...         BreakLabel1;//(4)    }}

In (1), break interrupts an internal iteration (inner-iteration) and returns to an external iteration (outer-iteration);

In (2), continue skips the following statement, returning to the beginning of the internal iteration (inner-iteration) and continuing with the next internal iteration (inner-iteration);

In (3), continue Label1 interrupts both internal iterations (inner-iteration) and external iterations (outer-iteration), jumps directly to the Label1, and then it actually continues the iterative process, But it starts from an external iteration (outer-iteration);

In (4), Break Label1 interrupts all iterations and goes back to Label1, but no longer iterates.

The following example shows a tagged break and continue

inti = 0; outer: for(;true;) {Inner: for(; i < ten; i++) {println ("I =" +i); if(i = = 2) {println ("Continue"); Continue; }        if(i = = 3) {println ("Break"); I++;  Break; }        if(i = = 7) {println ("Continue outer"); I++; Continueouter; }        if(i = = 8) {println ("Break Outer");  Breakouter; }         for(intk = 0; K < 5; k++) {            if(k = = 3) {println ("Continue inner"); Continueinner; }        }    }}/ * Output Results

i = 0
Continue inner
i = 1
Continue inner
i = 2
Continue
i = 3
Break
i = 4
Continue inner
i = 5
Continue inner
i = 6
Continue inner
i = 7
Continue outer
i = 8
Break outer
*/

The same rules apply to the while iteration.

The point to keep in mind is that the only reason you need to use tags in Java is because there are loop nesting, and you want to easily break and continue from multiple layers of nesting

4.6 Switch

Switch is also sometimes classified as a choice statement. Depending on the value of an integer expression, the switch statement can be selected from a series of code to execute. It has the following format:

Switch (integral-selector) {    case integral-value1:statement ;  break;      case integral-value2:statement;  Break ;      case integral-value3:statement;  Break ;     //  ...    default : statement;}

where the Integral-selector (integer selection factor) is an expression that produces a numeric value, switch can compare the result of the expression to each integral-value (integer value). If a match is found, execute the corresponding statement (single statement or multiple statements, which do not require parentheses). If no match is found, the default statement is executed.

In the definition above, you will notice that each case ends with a break, which allows the execution process to jump to the end of the switch topic. This is a traditional way of building a switch statement, but break is optional. If break is omitted, the subsequent case statement (if any) continues to be executed until a break is encountered. Note that the last default statement has no break because the execution process has reached the break's jump destination, and of course, it is entirely possible to place a break at the end of the default statement, although doing so is of no use.

It is important to note that the selection factor in switch can only be an integer of int or char, and cannot use a string or a floating-point number

ImportJava.util.*; Public classvowelsandconsonants { Public Static voidMain (string[] args) {random random=NewRandom (1972);  for(inti = 0; I < 5; i++) {            intc = Random.nextint (+) + ' a '; println ((Char) C + "," + C + ":"); Switch(c) { CaseA :                 CaseE :                 CaseI :                 Case' O ' :                 Case' U ': println ("vowel");  Break;  Case' Y ': println ("Sometimes a vowel");  Break; default: println ("consonant"); }        }    }}

From this example, you can see that the case statements can be stacked together to form multiple matches for a piece of code. It is also important to note that the break statement is placed at the end of a particular case, otherwise the control flow will simply move down and handle the following case

[Thinking in Java] Chapter 4th-Controlling the execution process

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.