[Java Programming Ideas-Learning Notes] Chapter 4th controlling the execution process

Source: Internet
Author: User
Tags case statement

4.1 Return

The keyword return has two purposes: to specify a value to return at the end of a method, and to forcibly end the entire method at the return position, as follows:

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

As above, if the variable score is greater than or equal to 90, the entire method is ended in line 3rd, and the character ' A ' is returned, if it is greater than or equal to 80, the entire method is ended in line 5th, and the character ' B ' is returned, and so on, if score is less than 60, the entire method is terminated in line 11th Note that the above comment, although the comment is removed logically makes sense, but the computer can not understand the human logic, so when the method is a return value (depending on the void method is a method without return value), theif statement is used with the else .

If you are returning a method with a value of void ,return causes the method to end prematurely in the current position, and if you do not add a return, the end of the method will have an implicit return

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

The syntax of If-else has been shown in the previous section, and it should be emphasized that no numbers can be taken tomake conditional judgments, while,Do-while , and for The condition of the loop cannot be judged by numbers, although we know that C and C + + can use numbers to determine true or false .

4.3 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;

Note: the only difference between while and Do-while is that statements in Do-while are executed at least once, even if the expression is evaluated to falsefor the first time. In the while loop structure, if the condition is falsefor 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 (non-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) {            out.println ("i =" + i + "J =" +< c13> 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, the statements are executed sequentially, either in the initialization or in the stepping section. In addition, the initialization section can have any number of definitions of the same type.

4.4 foreach Syntax

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

int New int [Ten];  for (int i = 1; I <=; i++)     -1] = i;  for (int  e:a)    out.println (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 For Loop    if(i% 9! = 0)Continue;//If it is not an integer multiple of 9, skip the following statement and proceed to the next iterationOUT.PRINTLN (i + ""));} println ();inti = 0; while(true) {i++; intj = i * 27; if(j = = 1269) Break;//if J equals 1269, exit while Loop    if(i% 10! = 0)Continue;//If I is not an integer multiple of 10, skip the following statement and proceed to the next iterationOUT.PRINTLN (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), jumping directly to the Label1 , It then actually continues the iterative process, but begins with an external iteration (outer-iteration);

In (4), breakLabel1 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) {out.println ("Continue"); Continue; }        if(i = = 3) {out.println ("Break"); I++;  Break; }        if(i = = 7) {out.println ("Continue outer"); I++; Continueouter; }        if(i = = 8) {out.println ("Break Outer");  Breakouter; }         for(intk = 0; K < 5; k++) {            if(k = = 3) {out.println ("Continue inner"); Continueinner; }        }    }}/*Output i = 0continue Inneri = 1continue Inneri = 2continuei = 3breaki = 4continue Inneri = 5continue Inneri = 6continue I Nneri = 7continue outeri = 8break 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 continuefrom multiple layers of nesting.

4.6 Switch

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

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

whereselector(selection factor) is an expression capable of producing an integer number (or String type),switch can compare the result of this expression to each 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. With respect to selector, the jdk1.7 could not have been a string type before, and starting with jdk1.7, it could be either an integral type or a string type.

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 body. 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, you can completely A break is placed at the end of the statement, although doing so is of no use.

 Public classvowelsandconsonants { Public Static voidMain (string[] args) {random random=NewRandom (1972);  for(inti = 0; I < 5; i++) {            intc = Random.nextint (+) + ' a '; Out.println ((Char) C + "," + C + ":"); Switch(c) { CaseA :                 CaseE :                 CaseI :                 Case' O ' :                 Case' U ': out.println ("vowel");  Break;  Case' Y ': out.println ("Sometimes a vowel");  Break; default: Out.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

[Java Programming Ideas-Learning Notes] 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.