Java Basics--Loop and Selection Structure Statement

Table of contents

Select structure:

if...else statement:

switch statement:

Loop structure:

while loop:

do-while loop:

for loop:

Enhanced for loop:

jump statement

break keyword

continue keyword

Comprehensive example


Loop and selection structures are commonly used control statements in Java programs, which are used to control the execution flow of the program. The following briefly describes the syntax and usage of loop and select constructs.

Select structure:

  • if...else statement:

It is used to judge whether to execute a certain block of code according to the condition.

The syntax format is as follows:

if(布尔表达式 1){
   //如果布尔表达式 1的值为true执行代码
}else if(布尔表达式 2){
   //如果布尔表达式 2的值为true执行代码
}else if(布尔表达式 3){
   //如果布尔表达式 3的值为true执行代码
}else {
   //如果以上布尔表达式都不为true执行代码
}

An if statement can be followed by an else if...else statement, which can detect multiple possible conditions. When using if, else if, else statements, you need to pay attention to the following points:

  1. An if statement has at most one else statement, and the else statement follows all the else if statements.
  2. An if statement can have several else if statements, which must precede the else statement.
  3. Once one of the else if statements is detected as true, the other else if and else statements will skip execution.
  • switch statement:

Match different case branches according to the value of the expression for execution.

The syntax format is as follows:

switch (expression) {
    case value1:
        // 执行语句块
        break;
    case value2:
        // 执行语句块
        break;
        //你可以有任意数量的case语句
    ...
    default:
        // 执行语句块

}

When using the switch statement, you need to pay attention to the following points: 

  1. Variable type: The variable type in the switch statement can be byte, short, int, char or String (Java SE 7+).
  2. Multiple case statements: A switch statement can have multiple case statements, each followed by a value to compare and a colon.
  3. The value of the case statement: The data type of the value in the case statement must be the same as the data type of the variable, and it can only be a constant or a literal constant.
  4. Execution sequence: When the value of the variable is equal to the value of the case statement, the execution starts from the matched case statement, and the switch statement will not be jumped out until a break statement is encountered.
  5. Break statement: When a break statement is encountered, the switch statement terminates, and the program jumps to the statement following the switch statement for execution. If there is no break statement, the program will continue to execute the next case statement until a break statement is encountered.
  6. default branch: The switch statement can contain a default branch, which is usually placed in the last position. When there is no matching case statement, the default branch is executed, which does not require a break statement.

Loop structure:

  • while loop:

When the loop condition is satisfied, a block of code is repeatedly executed until the loop condition is not satisfied.

while is the most basic loop, the syntax format is as follows:

while( 布尔表达式 ) {
  //循环内容
}

The loop will continue executing as long as the Boolean expression is true. 

  • do-while loop:

For the while statement, if the condition is not met, the loop cannot be entered. But sometimes we need to execute at least once even if the condition is not met. The do...while loop is similar to the while loop, the difference is that the do...while loop executes the code block of the loop body once, and then executes repeatedly when the loop condition is satisfied until the loop condition is not satisfied.

The syntax format is as follows:

do {
       //代码语句
}while(布尔表达式);

Note: The Boolean expression comes after the loop body, so the statement block is executed before the Boolean expression is checked. If the Boolean expression evaluates to true, the block of statements executes until the Boolean expression evaluates to false. 

  • for loop:

Although all loop structures can be represented by while or do...while, Java provides another statement - for loop. The for loop statement is the most commonly used loop statement, which makes some loop structures easier.

The number of times the for loop executes is determined before execution. The syntax format is as follows:

for(初始化表达式; 循环条件; 操作表达式)
{
	执行语句
	...
}

Here are a few things to say about the for loop: 

  1. Initialization expression: Before entering the loop, perform an initialization operation. Loop control variables can be declared and initialized.
  2. Loop Condition: Before each loop iteration begins, the value of the boolean expression of the loop condition is checked. If true, continue executing the loop body; if false, exit the loop immediately.
  3. Execute Statements: At each loop iteration, the statements in the loop body are executed.
  4. Operation expression: After each loop iteration, the operation expression is executed. Typically used to update the value of a loop control variable.
  5. Going back to step 2: After executing the action expression, check the value of the loop condition again. If the condition is still true, continue to execute the next loop iteration; if the condition is false, break out of the loop and execute the statement after the loop.
  • Enhanced for loop:

Java5 introduced an enhanced for loop mainly for arrays. Java's Enhanced for Loop (Enhanced for Loop), also known as for-each loop, is a simplified syntax for traversing an array or collection. It provides a convenient iterative access to elements in arrays or collections, providing a concise way to work with these containers.

The syntax of the enhanced for loop is as follows:

for (元素类型 变量名 : 数组或集合) {
    // 执行语句
    ...
}

Among them, the element type represents the type of elements in the array or collection, the variable name represents the variable name that receives the current element in each iteration, and the array or collection is the object to be traversed iteratively.

When using the enhanced for loop, the traversal process will automatically fetch each element in the array or collection in order, assign it to a variable, and execute the corresponding code block. There is no need to specify an index or do manual iteration control, the loop ends automatically.

For example, when iterating over an array of integers, you can use the enhanced for loop:

int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}

The above code will output each element in the array in turn: 1, 2, 3, 4, 5.

It should be noted that the enhanced for loop is only applicable to the case where each element in the container is accessed and processed, and it cannot be used to modify the elements in the container or obtain the iteration index.

jump statement

break keyword

break is mainly used in loop statements or switch statements to jump out of the entire statement block.

break Breaks out of the innermost loop and continues execution of the statement below that loop.

continue keyword

Using the continue keyword in any loop structure (for loop, while loop, do-while loop), its effect is to immediately skip the remaining code of the current loop iteration and directly enter the next loop iteration.

in particular:

  • In the for loop, when the program executes to the continue statement, it will immediately jump to the update statement, and then proceed to the next loop iteration.
  • In the while or do...while loop, when the program executes to the continue statement, it will immediately jump to the judgment statement of the Boolean expression, and then continue to the next round of loop judgment.

In this way, the program can skip the code of the current loop iteration and enter the next loop when a certain condition is met, so as to realize a specific control flow.

It should be noted that continue will only affect the current single loop body, and will not jump out of the entire loop. If you want to terminate the loop completely, you can use the break keyword.

Comprehensive example

Below is an example of Java code that uses a combination of select statements and loop constructs.

public class LoopAndSelectionExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        // 使用for循环遍历数组元素
        for (int num : numbers) {
            if (num % 2 == 0) {
                System.out.println("偶数:" + num);
            } else {
                System.out.println("奇数:" + num);
            }

            // 使用switch语句根据数字的值做出不同的处理
            switch(num) {
                case 1:
                    System.out.println("数字为1");
                    break;
                case 2:
                    System.out.println("数字为2");
                    break;
                default:
                    System.out.println("其他数字");
                    break;
            }

            // 如果数字为3,则跳过当前迭代,继续下一次迭代
            if (num == 3) {
                continue;
            }
            // 如果数字为5,则终止整个循环
            else if (num == 5) {
                break;
            }

            int count = 0;
            // 使用while循环进行计数输出
            while (count < num) {
                System.out.print(count + " ");
                count++;
            }
            System.out.println();

            int i = 0;
            // 使用do-while循环进行计数输出
            do {
                System.out.print(i + " ");
                i++;
            } while (i <= num);
            System.out.println();
        }
    }
}

This code demonstrates how to use loop constructs and select statements to process an array of integers. In the for loop, traverse the array elements and judge the parity, and execute the corresponding output statement. Use a switch statement to do different things depending on the value of the number. Judging by the if condition, use the continue keyword to skip the iteration where the number is 3, and use the break keyword to terminate the loop traversal when the number is 5. At the same time, use the while loop and do-while loop to output the count according to the size of the number respectively.

Guess you like

Origin blog.csdn.net/m0_74293254/article/details/132243478