Structure of Java Foundation-->> conditional structure and cyclic structure

Source: Internet
Author: User

Program flow control Statements in Java include conditional structure, loop structure, and jump statements

4.1-Piece structure

The conditional structure includes the sequential structure and the selection structure. The sequential structure does not jump and judge in program execution until the program is finished. The selection structure includes the IF statement, the If-else statement, and the switch statement, which can change the execution process of the program during program execution.

4.1.1 If statement

An If statement is a syntactic structure that is processed after conditional judgment

if (conditional expression) {     //   One or   more statements executed after a condition }// The value of a conditional expression can only be a Boolean type false/true

4.1.2 If-else Statements

The If-else statement is also known as a dual-branch selection structure

if (conditional expression) {  statement 1           // When conditional expression is true, execute 1}else{  Statement 2           //  When the conditional expression is not true, execute 2}

Example:

int num1 =; int num2 =N; if (Num1 > num2) {  System.out.println ("num1 greater than num2");   } Else {  System.out.println ("num2 greater than Num1");   } // num2 greater than NUM1

4.1.3 if-else-if Statements

if(conditional expression 1) {//If conditional expression 1 is establishedStatement Block 1//code that executes the statement block 1}Else if(conditional expression 2) {//Otherwise, if conditional expression 2 is establishedStatement Block 2//code that executes the statement block 2}Else if(conditional expression N) {//if the conditional expression N is setStatement block N//code that executes the statement block N}....                           //make judgments about other conditionsElse{//if all the above conditions are not trueStatement Block n+1//Executes statement block n+1 Code }

According to the student's performance, determine which grade belongs to, and output:

classTwoday { Public Static voidMain (string[] args) {intScore = 100; if(score>=90) {System.out.println (Excellent); }Else if(Score >=80) {System.out.println (Good); }Else if(score>=60) {System.out.println (Qualified); }Else{System.out.println ("Non-conformities"); }    }}//Excellent

4.1.4 Nesting of SELECT statements

Nesting of SELECT statements refers to nested IF statements in an if statement

if (conditional expression 1            ) {if(conditional expression 2) {                statement block 1            }else{                    statement block 2}        }  Else{            if(conditional expression 3) {                statement block 3            }else{                    statement block 4                }        }

Use nested IF statements to determine the grade according to the student's performance

classTwoday { Public Static voidMain (string[] args) {intScore = 85; if(Score >=60){            if(score>=80){                if(score>=90) {System.out.println (Excellent); }Else{System.out.println (Good); }            }Else{System.out.println (Qualified); }        }Else{System.out.println ("Non-conformities"); }    }}//Liang

4.1.5 Switch statement

The switch statement is a multi-branch structure that can replace a complex if-else-if statement, where the result type of the expression can only be a byte, short, int, char type, and a switch statement is a multi-branch switching statement

 switch   (expression) { case   constant expression 1: statement group  1break  ;   case   2 break  ;  case              3 break  ; .....             default  : statement group N;}  

Output student scores with a switch statement:

classTwoday { Public Static voidMain (string[] args) {intScore = 80; intrank = SCORE/10;//convert 100-cent to 10-point system for easy judgment        Switch(rank) { Case10:             Case9: System.out.println (Excellent);  Break;  Case8:             Case7: System.out.println (Good);  Break;  Case6: System.out.println (Qualified);  Break; default: System.out.println ("Non-conformities"); }    }}//Liang

The difference between 4.1.6 if and switch

The IF statement and the switch statement structure are very similar, all are multi-branch SELECT statements, but the switch structure can only handle the equivalence of conditional judgment, and must be an integer variable or a character type variable, and the multi-if structure does not have this limitation. When using the switch structure, do not forget that each case ends with a break; Typically, the branch is over 3 layers, using the switch statement, if the condition determines a range, use the IF-ELSE-IF statement.

4.2 Cycle Structure

The loop structure generally includes for, while, Do-while a total of 3 loop statements

4.2.1 While loop statement

While loop first to determine whether the loop condition is satisfied, if the first cycle condition is not satisfied, directly out of the loop, the loop will not execute, while the characteristics of the loop, first judgment, after execution.

 while (Boolean expression) {     statement or statement block;   }

Using the while loop output 1~100

class Twoday {    publicstaticvoid  main (string[] args)      {        int i=1;          while (i<=100) {     // cyclic expression             System.out.println (i);            I+ +;    // loop variable self-increment 1         }    }}

4.2.2 Do-while Loop statement

The loop body statement after do is executed, and then the Boolean expression after the while is evaluated, and if true, the loop body after do is executed again, and the value of the Boolean expression is interpreted again. Otherwise, the Do-while feature is that the conditional expression is executed at least once, whether or not it is true or not.

 Do {   statement or statement block   }while (Boolean expression);

Output 1~100 via Do-while

class Twoday {    publicstaticvoid  main (string[] args)      {         int i=1;          Do {            System.out.println (i);     // do first execute the output once            i++;        }  while (i<=100);}    }

The difference between 4.2.3 while and Do-while

The while statement is executed after judgment, Do-while is executed first, (if the conditional expression is not true, the while is not executed. The Do-while statement is executed at least once).

4.2.4 for Loop statement

 for (initialize an expression; a conditional expression; an iteration statement) {A    loop body statement;}

The initialization expression executes only once before the loop, usually as the definition of the iteration variable. The conditional expression is a Boolean expression that, when the value is true, proceeds to execute the Loop body statement for the For statement, which iterates over the statements that are used to change the loop condition, such as self-increment, self-subtraction, and so on.

The execution procedure for the FOR Loop statement:

① executing an initialization expression

② evaluates the intermediate conditional expression value, and if true, resumes execution of the following loop body statement

③ performs an iterative representation of the delta, changing the value of the loop variable

④ repeats the previous two steps, starting the next loop until the middle of the conditional expression is false, ending the entire loop statement

Output 1~100 with For loop

class Twoday {    publicstaticvoid  main (string[] args)      {        for (int i=0;i<=100;i++) {    // define loop variable, loop statement, initialization value is 0;             System.out.println (i);}}    }

Note: Even if the expression is empty, the semicolon ";" that separates the 3 expressions cannot be omitted.

 for (;;;) {}// legal, correct

4.2.5 Nested loop statements

①while Statement Nesting

 while (conditional expression 1)    {while(conditional expression 2) {    ...        }}            

②do-while Statement Nesting

         Do {            do{                ...            }  while (conditional expression 1);        }  while (conditional expression 2);

③for statement and while loop nesting

 for (;;) {    while(conditional expression) {...}}

④for Statement Nesting

 for (;;) {    for(;;) {...}}

⑤for Loop and Do-while loop nesting

 for (;;) {    do {...}  while (conditional expression);}

⑥while loops and for loop nesting

 while (conditional expression) {    for(;;) {...}}

⑦do-while loops and for loop nesting

 Do {    for(;;) {...}}  while (conditional expression);

⑧do-while Loop and while loop nesting

 Do {    while(conditional expression 1) {...}}  while (conditional expression 2);

⑨while Loop and Do-while loop nesting

 while (conditional expression 1) {    do {...}  while (conditional expression 2);}

Use nested loops to output right triangle with "*"

classTwoday { Public Static voidMain (string[] args) {intI, J;  for(i=0;i<6;i++) {//first loop control number of rows             for(j=0;j<i;j++) {//Second Cycle control * QuantitySystem.out.print ("*");//Output *} System.out.println (); //line Break        }    }}/*****************/

4.3 Jump statements

Jump statements have break,continue and return

4.3.1 Break Jump Statement

When the loop structure is executed into the break statement, it immediately stops the current loop and executes the statement below the loop

Use the break output 0~99 in the loop structure

 class   Twoday { public  static  void   main (string[] args) { int   I;  for  (I=1;i<101;i++ if  (I==100 bre       AK ; //         } System.out.println (i); }}}  //  1 2 3 4 5 ...  

When i=100, the break statement is executed, the loop is terminated, there can be multiple break statements in a loop, and break is not specifically used to terminate the loop, only in some cases to cancel a loop.

4.3.2 Continue jump Statement

Continue is to skip this loop and execute the next loop statement

class Twoday {    publicstaticvoid  main (string[] args)      {        int  i;          for (i=1;i<101;i++) {            if(i==3) {               /// when i=3, skip this loop and proceed to the back                continue;                }            System.out.println (i);}}    } // 1 2  4 5 ... about

The difference between 4.3.3 break and continue

The continue statement ends this loop only, rather than terminating the execution of the entire loop. The break statement ends the entire loop and no longer determines whether the condition of the execution loop is true.

4.3.4 return Jump Statement

The return statement terminates the current method run and returns to the statement that called the method, which also provides the corresponding return value

if (x>=0) {            returntrue;        }         return false ;    }

When the IF condition statement evaluates to TRUE, executes the first return statement, exiting the method. The following (return false) skip does not execute

Thank you very much < from scratch to learn java> a book on my help, this article by this, only for learning, review, consolidation. Thanks again.

Structure of Java Foundation-->> conditional structure and cyclic structure

Related Article

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.