JavaSE - process control

JavaSE - process control

Learning objectives of this section:

  • Be familiar with and master the use of compound sentences;
  • Be familiar with and master the use of conditional sentences;
  • Be familiar with and master the use of circular sentences;
  • Be familiar with and master the use of loop control statements;

1. Overview of process control

Process control is very important for any programming language. It provides the basic means to control program steps.

Process control statements are statements that control the execution order of statements in the program. Statements can be combined into small logic modules that can complete certain functions.

Process control statements are divided into four categories according to different functions:

  • Compound statement;
  • Conditional statements;
  • Loop statement;
  • Loop control statement.

2. Compound statement

Like C language and other languages, the compound statement of Java language is a statement with the whole block as the unit, so it is also called block statement. Compound statements are surrounded by braces ({}).

In the previous study, the class body is marked with "{}" as the start and end, and so is the method body. Each statement in a compound statement is executed from top to bottom.

  • In the method body, the statements in the code block are executed from top to bottom. Pay attention to the use range of local variables.

Write code to test:

public class CompoundSentence {
    public static void main(String[] args) {
        int a = 10;
        {
            int b = 6;
            System.out.println("b=" + b);
            {
                System.out.println("a+b=" + (a + b));
            }
        }
        System.out.println("Hello World!");
    }
}

Operation results:

b=6
a+b=16
Hello World!
  • In the class body, there are two cases of using code blocks:
    • Static code block: a code block modified by the keyword static. The code in this code block will be executed only once when the class is loaded. It is mainly used to initialize class variables (variables modified by static keyword).
    • Non static code block: the code in this code block will be executed when creating such an object. It is mainly used to initialize instance variables.

Write code to test:

public class Person {
    {
        System.out.println("Non static code block executed!");
    }
    static {
        System.out.println("Static code block executed!");
    }

    public static void main(String[] args) {
        Person p1 = new Person();
        Person p2 = new Person();
        Person p3 = new Person();
    }
}

Test results:

Static code block executed!
Non static code block executed!
Non static code block executed!
Non static code block executed!

3. Conditional statements

Conditional statements can execute different statements according to different conditions.

There are two kinds of conditional statements: if else conditional branch statements and switch case multi branch statements.

3.1 if else conditional branch statement

When you learned the conditional operator (?:) in the previous section, you had a simple understanding of conditional branching statements.

  • if simple branch statement

The syntax is as follows:

if (Boolean expression) {
    Statement 1;
    Statement 2;
    ...
}

If the value of Boolean expression is true, the statement in * * if statement block * * will be executed; otherwise, it will not be executed.

  • If else statement

The syntax is as follows:

if (Boolean expression) {
    sentence;
    ...
} else {
    sentence;
    ...
}

If the value of the Boolean expression is true, the statements in the * * if statement block are executed; otherwise, the statements in the else statement block * * are executed.

  • if...else if multi branch statement

The syntax is as follows:

if (Boolean expression 1) {
    sentence;
    ...
} else if (Boolean expression 2) {
    sentence;
    ...
}
...
else if (Boolean expression N) {
    sentence;
    ...
} else {
    sentence;
    ...
}

At this time, Boolean expressions will be evaluated from top to bottom. Once the value of a Boolean expression is true, the statement of the block where the Boolean expression is located will be executed, and the following statements will not be executed.
If all Boolean expressions are false, the statements within the else statement block are executed (if there is no else statement block, no statements within the statement block are executed).

Write code to test:

public class ConditionalSentenceIf {
    public static void main(String[] args) {
        
        int a = 5;
        
        if (a == 4) {
            System.out.println("Hello World!");
        } else {
            System.out.println("Do Hello World!");
        }
        
        char b = 'C';
        
        if (b == 'A') {
            System.out.println("b=A");
        } else if (b == 'B') {
            System.out.println("b=B");
        } else if (b == 'C') {
            System.out.println("b=C");
        }
        
    }
}

Operation results:

Do Hello World!
b=C

3.2 switch case multi branch statement

if...else if multi branch statement if there are many else if code blocks, the code written will be very cumbersome, redundant and messy, affecting reading;

In Java, switch case multi branch statements can be used instead of:

switch (expression) {
    case Constant 1: {
        Statement block;
        [break;]
    }
    case Constant 2: {
        Statement block;
        [break;]
    }
    ...
    case constant N: {
        Statement block;
        [break;]
    }
    default: {
        Statement block;
        [break;]
    }
}

The value of the expression in the switch statement must be integer, character type, enumeration type (new in Java 5) and string (new in Java 7), and constants 1~N must also be integer, character type or string.
The switch statement will first calculate the value of the expression. If the value of the expression is the same as the constant value after a case, the statement blocks in the case and subsequent cases will be executed. Until a break statement is encountered.
If the value of the expression is different from the constant value after any case, the statements in the default statement block will be executed (if there is no default block, no statements will be executed).

Write code to test:

public class ConditionalSentenceSwitch {
    public static void main(String[] args) {
        int a = 3;
        switch (a + 1) {
            case 3: {
                System.out.println("Statement block 3 is executed");
            }
            case 4: {
                System.out.println("Statement block 4 is executed");
            }
            case 5: {
                System.out.println("Statement block 5 is executed");
                break;
            }
            case 6: {
                System.out.println("Statement block 6 is executed");
            }
        }
        String str = "123";
        switch (str) {
            case "234": {
                System.out.println("Statement block 234 is executed");
            }
            case "345": {
                System.out.println("Statement block 345 is executed");
            }
            default: {
                System.out.println("Statement block default Executed");
            }
        }
    }
}

Operation results:

Statement block 4 is executed
 Statement block 5 is executed
 Statement block default Executed

3.3 using the Scanner class to enter data from the keyboard

If we want to use the keyboard to input data into the program, we need to use the Scanner class. The Scanner class provides many input methods:

  • nextByte: enter byte type data from the keyboard;
  • nextShort: enter short type data from the keyboard;
  • nextInt: input int type data from the keyboard;
  • nextLong: input long type data from the keyboard;
  • nextFloat: enter float type data from the keyboard:
  • nextDouble: enter double type data from the keyboard;
  • nextBoolean: enter boolean type data from the keyboard;
  • nextLine: input string type data from the keyboard;

These input methods can only input data of the corresponding type (or other types of data that can be converted to the current type of data), otherwise an error will be reported.

How to use the Scanner class: use the constructor to create a Scanner object and pass in the System.in stream as a parameter:

Scanner scanner = new Scanner(System.in);

Write code to test:

import java.util.Scanner;
public class ScannerTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        System.out.println("Entered a The value of is" + a);
        scanner.close(); // It is recommended that the close method be closed after scanner has been used.
    }
}

Input: 4, operation result:

4. Circular statement

Circular statement is to repeatedly execute an operation under certain conditions. Three common loop statements are provided in Java, namely, while loop statement, do while loop statement and for loop statement.

4.1 while loop statement

The while loop statement uses a Boolean expression to control whether to continue repeating the statement block:

while (Boolean expression) {
    Statement block;
}

Calculates the value of the Boolean expression. When the value of the Boolean expression is true, the statement in the statement block is executed. After executing the statements in the statement block, recalculate the value of the Boolean expression and execute the loop.
Exit the loop until the value of the Boolean expression is false.

Write code to test:

public class LoopSentenceWhile {
    public static void main(String[] args) {
        int x = 1;
        while (x <= 5) {
            System.out.println("x=" + x);
            x++;
        }
    }
}

Operation results:

x=1
x=2
x=3
x=4
x=5

4.2 do while loop statement

Do while loop statements are similar to while loop statements. The difference between them is that while loop statements need to judge whether the condition is true, while do while loop statements need to execute the statement block once before judging whether the condition is true.
That is, the statement block of the do while loop statement must be executed at least once. The syntax is as follows:

do {
    Statement block;
} while (Boolean expression);

Test with the code in Section 4.1:

public class LoopSentenceDoWhile {
    public static void main(String[] args) {
        int x = 1;
        do {
            System.out.println("x=" + x);
            x++;
        } while (x <= 5);
    }
}

Operation results:

x=1
x=2
x=3
x=4
x=5

4.3 for loop statement

For loop is one of the most useful loop statements in Java programming. A for loop can be used to repeatedly execute a statement until a condition is met. foreach syntax was added after Java 5.

The syntax of the for statement is as follows:

for (Expression 1, Expression 2, Expression 3) {
    Statement block;
}
  • Expression 1: initialization expression, which is responsible for completing the initialization of variables. It will only be executed once during the for loop;
  • Expression 2: Boolean expression, which is used to specify the loop condition. When a for loop is executed, it is executed once before each loop;
  • Expression 3: Post loop operation expression, which is responsible for trimming variables and changing loop conditions. During the for loop, it is executed once after each loop.

During the for loop, first execute expression 1 to complete the initialization of a variable; Then evaluate expression 2. If the value is true, execute the statement block and cycle once. Expression 3 is executed immediately after the statement block is executed,
This part is usually an expression to increase or decrease the loop control variable. After the execution of expression 3, the cycle ends. The second round of loop starts from expression 2. If the value is true, the loop will continue. If the value is false, the whole for loop statement will jump out.

Write statements to test:

public class LoopSentenceFor {
    public static void main(String[] args) {
        for (int x = 0; x < 5; x++) {
            System.out.println("for The loop is executed" + x + "second");
        }
    }
}

Operation results:

for Loop executed 0 times
for The loop was executed once
for The loop was executed twice
for The loop was executed 3 times
for The loop was executed 4 times

The foreach statement is a special simplified version of the for loop and cannot completely replace the for statement, but any foreach statement can be rewritten into a for statement.
Foreach is not a keyword. It is customary to call this special format of for statement foreach statement. It provides great convenience for programmers in traversing arrays.

The syntax is as follows:

for (Element variable: Array object) {
    Statement block;
}

The element variable in the foreach statement does not need to be initialized. The element variable is used to traverse the array object, and each element of the data object is traversed until each element is traversed once, and then the loop ends.

Write code to test:

public class LoopSentenceForeach {
    public static void main(String[] args) {
        int[] list = {1, 2, 3, 4, 5};
        for (int x: list) {
            System.out.println("x=" + x);
        }
    }
}

Operation results:

x=1
x=2
x=3
x=4
x=5

5. Loop control statement

Java provides two keywords: break and continue to control the jump of the loop.

  • The break statement jumps out of the whole loop;
  • The continue statement jumps out of this loop.

If the loop condition of the loop statement is always true (for example, the Boolean expression directly writes true), the loop will continue to execute. This loop is called "dead loop".
Not only can not let the program execute in sequence, but also consume system resources. In severe cases, the program can crash.
In the process of writing code, we must carefully check the loop conditions to prevent "dead loop".

5.1 break statement

Use the break statement to jump out of the switch structure:

public class BreakSwitch {
    public static void main(String[] args) {
        int x = 1;
        switch (x) {
            case 1: {
                System.out.println("Yes case1");
                // If there is no break here, the subsequent case will be executed
            }
            case 2: {
                System.out.println("Yes case2");
                break; // After the break jumps out of the switch, the subsequent case s will not be executed again
            }
            case 3: {
                System.out.println("Yes case3");
            }
        }
    }
}

Operation results:

Yes case1
 Yes case2

You can also jump out of a loop using the break statement:

public class BreakLoop {
    public static void main(String[] args) {
        int a = 1;
        while (a < 5) {
            if (a == 3) {
                break; // When the value of a increases to 3, it jumps out of the while loop
            }
            System.out.println("Yes while loop" + a + "second");
            a++;
        }
        int b = 1;
        do {
            System.out.println("Yes do-while loop" + b + "second");
            if (b == 3) {
                break; // When the value of b increases to 3, it jumps out of the do while loop
            }
            b++;
        } while (b < 5);
        for (int c = 1; c < 5; c++) {
            System.out.println("Yes for loop" + c + "second");
            if (c == 3) {
                break; // When the value of c increases to 3, it jumps out of the for loop
            }
        }
    }
}

Operation results:

Yes while Cycle once
 Yes while Cycle 2 times
 Yes do-while Cycle once
 Yes do-while Cycle 2 times
 Yes do-while Cycle 3 times
 Yes for Cycle once
 Yes for Cycle 2 times
 Yes for Cycle 3 times
  • If the loop is nested, the break statement can only jump out of the loop body where the statement is located, and the outer loop cannot jump out.

If you want break to jump out of the outer loop, Java provides the function of tag. The syntax is as follows:

Tag name: Circulatory body {
    break Tag name;
}

Write code to test:

public class BreakExternalLoop {
    public static void main(String[] args) {
        xLoop: for (int x = 0; x < 5; x++) {
            for (int y = 0; y < 5; y++) {
                if (x == 3) {
                    break xLoop;
                }
                System.out.print("y=" + y);
            }
            System.out.println("x=" + x);
        }
    }
}

Operation results:

y=0y=1y=2y=3y=4x=0
y=0y=1y=2y=3y=4x=1
y=0y=1y=2y=3y=4x=2

You can see that when the value of x increases to 3, the if statement is established, execute the break statement, and directly jump out of the specified outer loop body.

5.2 continue statement

The continue statement is a supplement to the break statement. Continue does not immediately jump out of the loop body, but skips the statements before the end of the loop, returns to the conditional test part of the loop, and restarts the execution of the loop.

Write code to test:

public class ContinueLoop {
    public static void main(String[] args) {
        int a = 0;
        while (a < 5) {
            a++;
            if (a == 3) {
                continue; // Jump out of this cycle when the value of a increases to 3
            }
            System.out.println("Yes while loop" + a + "second");
        }
        int b = 0;
        do {
            b++;
            if (b == 3) {
                continue; // Jump out of this cycle when the value of b increases to 3
            }
            System.out.println("Yes do-while loop" + b + "second");
        } while (b < 5);
        for (int c = 1; c <= 5; c++) {
            if (c == 3) {
                continue; // Jump out of this cycle when the value of c increases to 3
            }
            System.out.println("Yes for loop" + c + "second");
        }
    }
}

Run test:

Yes while Cycle once
 Yes while Cycle 2 times
 Yes while Cycle 4 times
 Yes while Cycle 5 times
 Yes do-while Cycle once
 Yes do-while Cycle 2 times
 Yes do-while Cycle 4 times
 Yes do-while Cycle 5 times
 Yes for Cycle once
 Yes for Cycle 2 times
 Yes for Cycle 4 times
 Yes for Cycle 5 times

You can see that when the above loops are executed for the third time, the continue statement will directly jump out of this loop, so the output statement after the continue statement will not be executed.

Tags: Java JavaSE

Posted on Sun, 24 Oct 2021 00:03:31 -0400 by iceman2g