JavaSE basics-(4) sequence, selection, loop structure and control jump statement

table of Contents

1. Sequence structure

Second, choose the structure

2.1 if statement

2.2 switch statement

Three, cycle structure

3.1 for statement

3.2 while statement

3.3 do while statement

3.4 The difference between the three loop statements

Four, control jump statements

4.1 continue statement

4.2 break statement

4.3 return statement


 

The flow control statement in Java can control the execution flow of the program.

Generally can be divided into three categories:

  • Sequence structure
  • Choose a structure
  • Cyclic structure

 

1. Sequence structure

The sequence structure is very simple, running the code line by line.

From top to bottom, execute in order.

We use the following code to test the execution steps of the sequential structure:

System.out.println(1);
System.out.println(0);
System.out.println(2);
System.out.println(4);

The following is the result of the execution:

Second, choose the structure

The selection structure is generally divided into:

  • if statement
  • switch statement

 

2.1 if statement

The execution flow of the if statement is to first calculate the value of the expression,

If the return value of the expression is true, the statement following the if condition is executed,

If the return value of the expression is false, if there is an else statement, the statement following the else statement is executed. Its general form is as follows:

if(Comparison expression 1){
    do A;
}
else{
    do B;
}

It should be noted that the return value of the judgment statement after the if must be of type boolean, and it cannot be true if a non-zero number is written directly in it like C++.

We test the selection structure:

public class Main {
    public static void main(String[] args){
        boolean workhard=true;
        if(workhard)
            System.out.println("Success :)");
        else
            System.out.println("Fail :(");
    }
}

Here is the result:

 

If we want the if statement to handle multiple results, then the two branches of if-else are obviously not enough. At this time, we need to use the else if statement:

if(Comparison expression 1){
    do A;
}
else if(Comparison expression 2){
    do B;
}
else if(Comparison expression 3){
    do C;
}
else{
    do D;
}

The execution process is to first look at comparison expression 1, if it is true, execute statement A, if it is false, then look at comparison expression 2.

If comparison expression 2 is true, execute statement B, if it is false, see comparison expression 3.

If the comparison expression 3 is true, execute statement C, if it is false, execute statement D directly.

We use a piece of code to contact the use of the else if statement:

public class Main {
    public static void main(String[] args){
        int age=21;
        if(age<18)
            System.out.println("Child");
        else if(age<50)
            System.out.println("Adult");
        else
            System.out.println("The aged");
    }
}

The following is the running result of the program:

Compared with the following swtich statement, the if statement is more suitable for judging the interval or range.

 

2.2 switch statement

Compared with the if statement, the switch statement is more suitable for use when judging a fixed value. The general form is as follows:

switch(expression e){
    case value1:
        do code1;
        break;
    case value2:
        do code2;
        break;
    ...
    ...
    default:
        do codeN+1;
        break;
}

The data type of the expression e can be a basic data type and a reference data type,

The basic data types are byte, short, char, int, (mainly data that can be directly converted to int type without loss of precision)

Reference data types are enumerated types (JDK1.5) and String strings (JDK1.7)

We take the String type as an example for code testing:

public class Main {
    public static void main(String[] args){
        String language="Java";
        switch (language){
            case "Java":
                System.out.println("Java天下第一");
                break;
            case "C++":
                System.out.println("C++天下第一");
                break;
            case "C":
                System.out.println("C语言天下第一");
                break;
                default:
                    System.out.println("Python天下第一");
        }
    }
}

The results are as follows:

There are several issues to pay attention to:

  • The following case must be a constant, not a variable
  • The break statement must be written, otherwise the statement of the case later may be executed
  • The default statement can be written in any position, but it is recommended to write it at the end
  • The ending condition of the switch statement is to encounter break or the closing brace of switch

 

Three, cycle structure

There are mainly three loop structures: for, while, and do while.

3.1 for statement

The format of the for statement is generally as follows:

for(初始条件语句;条件表达式;循环后操作表达式){
    循环语句;
}

The execution process is the same as C++. First, the initial conditional statement will be executed, and then the conditional expression will be executed.

If the conditional expression is false, the loop is ended, if it is true, the loop statement is executed, and then the operation expression after the loop is executed.

Then the conditional expression is judged, if it is false, the loop is ended, if it is true, the loop statement and the operation expression after the loop are executed to loop.

Let's take the Helloworld output 10 times as an example to implement the code for the for loop:

public class Main {
    public static void main(String[] args){
        for(int i=0;i<10;i++){
            System.out.println("HelloWorld!");
        }
    }
}

The following is the output:

 

3.2 while statement

The format of the while statement is generally as follows:

初始化语句;
while(判断条件语句){
    循环体语句;
    控制条件语句;
}

The execution steps generally execute the initialization statement first,

Then execute the judgment condition statement, if it is false, the loop is ended,

If it is true, the loop body statement and the control condition statement are executed,

After the end, execute the judgment condition statement to loop.

Let's take the example of outputting Helloworld 10 times to experiment with the while statement:

public class Main {
    public static void main(String[] args){
        int count=0;
        while(count<10){
            System.out.println("HelloWorld!(while语句)");
            count++;
        }
    }
}

The results of the operation are as follows:

 

3.3 do while statement

The do while statement is very similar to the while statement, and its general form is as follows:

初始化语句;
do{
    循环体语句;
    控制条件语句;
}while(条件控制语句);

The general procedure first executes the initialization statement, and then directly enters the loop body, executes the loop body statement and the control condition statement once,

Finally, it is judged whether the conditional control statement is true or false, if it is false, the loop is ended, if it is true, the next loop is entered, and then the loop body statement and the control condition statement are executed to loop.

We still use helloworld to test the do while statement:

public class Main {
    public static void main(String[] args){
        int count=0;
        do{
            System.out.println("HelloWorld!(do while语句)");
            count++;
        }while(count<10);
    }
}

The results are as follows:

 

3.4 The difference between the three loop statements

  • The do while statement will execute the statement in the loop body at least once, while the while and for loops will first determine whether the condition is true, and it is possible that a loop statement will end directly without execution.
  • If the variable of the control condition needs to be used outside the loop, use the while loop. Otherwise, use the for loop. Define the control condition variable in the initial condition statement of the for loop and release it at the end to improve the efficiency of memory usage.

 

Four, control jump statements

Control jump statements generally only appear in switch statements and loop statements.

Its function is to let the program jump out of the switch to select the structure or out of the loop body and then execute the subsequent statements in sequence.

Control jump statements generally include continue statement, break statement and return statement.

 

4.1 continue statement

As the name implies, continue means to continue, and it can only appear in the loop body.

When the program executes to the continue statement in the loop body, it will directly enter the next loop without executing the loop body statement following the continue statement.

Let's take the output of all odd numbers from 0 to 10 as an example to experience the effect of the continue statement:

public class Main {
    public static void main(String[] args){
        for(int i=0;i<=10;i++){
            if(i%2==0)
                continue;
            System.out.println(i);
        }
    }
}

The results of the operation are as follows:

It can be seen that when the remainder of i modulo 2 is 0 (that is, when i is an even number), the continue statement is executed, and then the next loop is entered, and the value of i is not output.

So the output is odd.

 

4.2 break statement

The break statement is similar to the continue statement, but when there is a big difference,

When the program executes to the break statement, not only the loop body statement after the break statement is not executed, but the next loop is not executed, and the loop is directly ended.

We replace the continue statement in the above example with break to test the effect:

It turns out that nothing is output, because the initial value of i is 0 at the beginning, which satisfies the condition that the modulus 2 remainder is 0, and the break statement is executed to jump out of the loop and the program ends.

So nothing is output.

Need to pay attention when using break

  • The break statement can only jump out of the loop body that contains it
  • If you use the break statement in the loop nest, you can't jump directly to the outermost loop, you can only jump one level outside

But if we want to use the break statement in the inner loop to jump directly to the outer loop, we need to add a mark.

We use a program as an example:

public class Main {
    public static void main(String[] args){
        flag:for(int i=0;i<10;i++){
            for(int j=0;j<10;j++){
                break flag;
            }
            System.out.println("你没有跳出外层循环!");
        }
    }
}

Let’s analyze, if we use a normal break statement, the inner loop will be jumped out, and then the content of the outer loop will be executed.

That is, the sentence "You did not jump out of the outer loop!" will be output,

But if we add an identifier, add an identifier in the outermost loop: flag (other names can also be used), and the naming rules for identifiers are the same as for variables.

And add flag after the break statement, what will the program output?

The answer is nothing, let's verify it:

There is a very interesting interview question about this label:

System.out.println("123");
http://www.baidu.com
System.out.println("321")

The interviewer may ask you whether this code can run?

At first glance, it seems that the line in the middle is not a sentence, it will definitely report an error.

But analyze it, the colon after http is just an identifier, and then add the comment "//" so the following sentence is commented out.

So the program will run normally and output 123 and 321.

 

4.3 return statement

The function of the return statement is to jump out of the method, not out of the loop.

Let's use the code to test the effect of the return statement.

public class Main {
    public static void main(String[] args){
        for(int i=0;i<10;i++){
            System.out.println("我要开始跳出方法了");
            return;
        }
        System.out.println("你好像没跳出方法");
    }
}

The results of its operation are as follows:

If we change the return statement to break, the result is as follows:

This is the difference between return and break.

Guess you like

Origin blog.csdn.net/weixin_39478524/article/details/109476937