day05_Process Control Statement

Keywords: Java

During the execution of a program, the execution order of each statement has a direct impact on the outcome of the program. Therefore, we must be clear about the execution process of each statement. Moreover, many times we want to achieve the desired functions by controlling the execution order of the statements. Classification of process control statements in java: order structure, branch structure (if, switch), loop structure(for, while, do...while).

Sequential structure

The most common program structure in any programming language is the sequential structure. The sequential structure is that the program executes line by line from top to bottom without any judgment or jump in between. If there is no flow control between the lines of code of the main method, the program always executes from top to bottom, with the top code executed first and the bottom code executed later.

Code Samples

public class Demo01Sequence {
    public static void main(String[] args) {
        //Sequential execution, running top-down according to the order of writing
        System.out.println(1);
        System.out.println(2);
        System.out.println(3);
    }
}

if branch statement

if statement first format:

Execution process:

  1. First calculate the value of the relationship expression
  2. Execute the statement body if the value of the relationship expression is true
  3. Do not execute the statement body if the value of the relationship expression is false
  4. Continue executing the following statement

Code Samples

import java.util.Scanner;

/*
Case: Enter the year from the keyboard, please output the total number of days in February of that year. Leap year 29 days in February, average year 28 days.

Leap year:
(1)Can be divided by 4, not by 100
(2)Divisible by 400
*/
public class Demo02If {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter a year:");
        int year = input.nextInt();
        int days = 28;
        //Conditional expression
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            // Conditional expression is true execution
            days++;
        }
        //Code after if
        System.out.println(year + "February of the year" + days + "day");
        input.close();

    }
}

If statement second format: if...else

Execute process

  1. First judge the relationship expression to see if it is true or false
  2. Execute statement body 1 if true
  3. Execute statement body 2 if it is false
  4. Continue executing the following statement

Code Sample

public class Demo03If {
    //Find the Maximum of Two Numbers
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        //Define variables to hold larger values of a and b
        int max;
        if (a > b) {
            max = a;
        } else {
            max = b;
        }
        System.out.println("Maximum:" + max); //Maximum: 20
        //These functions can be rewritten as ternary operators
        max = a > b ? a : b;
        System.out.println("Maximum:" + max); //Maximum: 20
    }

}

The third format of an IF statement is if...else if...else

Execute process

  1. First, determine the relationship expression 1 to see if it is true or false
  2. If true, execute body 1 and end the current multibranch
  3. If it's false, go ahead and judge Relational Expression 2 to see if the result is true or false
  4. If true, execute body 2 and end the current multibranch
  5. Continue to judge the relationship expression if it's false... see if the result is true or false
  6. ...
  7. If no relationship expression is true, execute the body n+1 and end the current multibranch.

Code Samples

/*
Determine student grade by specifying test results

- 90-100      excellent
- 80-89        good
- 70-79        good
- 60-69        pass
- 60 The following failures
 */
public class Demo04If {
    public static void main(String[] args) {
        int score = 89;
        if(score<0 || score>100){
            System.out.println("Your results are wrong");
        }else if(score>=90){
            System.out.println("Your results are excellent");
        }else if(score>=80){
            System.out.println("Your results are good");
        }else if(score>=70){
            System.out.println("Your achievements are good");
        }else if(score>=60){
            System.out.println("Your results are qualified");
        }else {
            System.out.println("Your grade was a failure");
        }
    }
}

Matters needing attention:

  • If the if statement controls the body of a statement, the curly braces may be omitted but not recommended!

Branch structure: if..else nesting

In the if statement block or else statement block, there is another conditional judgment (can be single branch, double branch, multi-branch)

Features of implementation:

  • If it is nested in an IF statement block, the internal condition will be determined only if the external if condition is satisfied
  • If it is nested in an else statement block, the internal condition will not be determined until the external if condition is not satisfied and the internal condition is entered into the else

Code Samples

/*
    Enter a year, month from the keyboard and output the total number of days in that month for that year
     Requirements: Positive year, January 1-12
*/
public class Demo05Test {
    public static void main(String[] args) {
        //Enter a year, month from the keyboard
        java.util.Scanner input = new java.util.Scanner(System.in);

        System.out.print("Particular year:");
        int year = input.nextInt();

        System.out.print("Month:");
        int month = input.nextInt();

        if (year > 0) {
            if (month >= 1 && month <= 12) {
                //Legal situation
                int days;
                if (month == 2) {
                    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                        days = 29;
                    } else {
                        days = 28;
                    }
                } else if (month == 4 || month == 6 || month == 9 || month == 11) {
                    days = 30;
                } else {
                    days = 31;
                }
                System.out.println(year + "year" + month + "Monthly" + days + "day");
            } else {
                System.out.println("Illegal month entry");
            }
        } else {
            System.out.println("Illegal year entry");
        }
    }
}

switch branch statement

Execution process:

  1. First calculate the value of the expression
  2. Second, compare with case in turn, once there is a corresponding value, the corresponding statement will be executed, and in the process of execution, the break will end.
  3. Finally, if all case s do not match the value of the expression, the default body part is executed and the program terminates.

Code Samples

/*
    Requirements: Keyboard entry week number shows today's weight loss activity.

    Monday: Running
    Tuesday: Swimming
    Wednesday: jogging
    Thursday: Motion Cycling
    Friday: Boxing
    Saturday: Mountain Climbing
    Sunday: Have a good meal

    Analysis:
        1. Keyboard input week data, receive with variable
        2. Multi-case judgment, implemented with switch statement
        3. Output corresponding weight loss plans in different case s
*/

import java.util.Scanner;

public class Demo06Switch {
    public static void main(String[] args) {
        // 1.Keyboard input week data, receive with variable
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter");
        int week = sc.nextInt();
        // 2.Multi-case judgment, implemented with switch statement
        switch (week) {
            // 3.Output corresponding weight loss plans in different case s
            case 1:
                System.out.println("Run");
                break;
            case 2:
                System.out.println("Swimming");
                break;
            case 3:
                System.out.println("Walk slowly");
                break;
            case 4:
                System.out.println("Motion bike");
                break;
            case 5:
                System.out.println("Boxing");
                break;
            case 6:
                System.out.println("Hill climbing");
                break;
            case 7:
                System.out.println("Have a good meal");
                break;
            default:
                System.out.println("Your input is incorrect");
                break;
        }
    }
}

Matters needing attention:

  • Switch (expression) can only have four basic data types (byte,short,int,char), two reference data types (enumerated after JDK1.5, String after JDK1.7)
  • case must be followed by a constant value and cannot be repeated

Case Penetration: In a switch statement, if no break is written after the case, a penetration occurs, that is, once the match is successful, the next case will not be judged and will run backwards until a break is encountered or the entire switch statement ends, and the switch statement execution terminates.

Code Samples

import java.util.Scanner;

/*
       Requirements: Keyboard entry weeks, output weekdays, rest days
       (1-5)Weekdays, (6-7) rest days
       
       
       case How does penetration occur?
       
           If a break statement is omitted from the switch statement, case penetration begins.
       
       Phenomena:
           When a case is started to penetrate, subsequent cases will have no matching effect and internal statements will be executed
           It doesn't end until you see a break or finish executing the overall switch statement.

   */
public class Demo07Switch {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the number of weeks:");
        int week = sc.nextInt();

        switch (week) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                System.out.println("Working day");
                break;
            case 6:
            case 7:
                System.out.println("Rest Day");
                break;
            default:
                System.out.println("Your input is incorrect");
                break;
        }
    }
}

Overview of loops

A loop statement can execute a piece of code repeatedly if the loop condition is met. This repetitive execution of code is called a loop body statement, when the loop condition is repeatedWhen executing this loop body, you need to modify the loop judgment condition to false at the appropriate time to end the cycle, otherwise the cycle will continue to execute and form an endless cycle. A cycle generally consists of the following four parts:

  • Initialization statement: Used to indicate the starting state of a loop when it opens, simply what happens when the loop starts
  • Conditional statement: Used to indicate the condition under which a loop repeats. Simply put, to determine if the loop can continue
  • Loop body statement: Used to indicate what a loop repeats, in short, what a loop repeats
  • Conditional control statement: Used to represent each change in the execution of a loop, simply to control whether the loop can be executed or not

for loop

Execution process:

  1. Execute Initialization Statement
  2. Execute the conditional judgment to see if the result is true or false. If false, the loop ends. If true, continue execution
  3. Execute Loop Body Statement
  4. Execute conditional control statements
  5. Back to Continue

Code Sample

//Requirements: Output all "daffodils" in the console, requiring 2 prints per line
public class Demo08For {
    public static void main(String[] args) {
        // 1.Defines the variable count, which holds the number of prints, with an initial value of 0
        int count = 0;
        for (int i = 100; i <= 999; i++) {
            int ge = i % 10;
            int shi = i / 10 % 10;
            int bai = i / 10 / 10 % 10;

            if ((ge * ge * ge + shi * shi * shi + bai * bai * bai) == i) {
                //  2.During the process of determining and printing the number of daffodils, stitch the spaces but do not wrap, and let count variable + 1 record the number printed
                System.out.print(i + " ");
                count++;
                // 3.After each count variable + 1, determine if a multiple of 2 has been reached, if yes, line break
                if (count % 2 == 0) {
                    System.out.println();
                }
            }
        }
    }
}

while Loop

Execution process:

  1. Execute the initialization statement (1) to complete the initialization of loop variables;
  2. Execute the loop condition statement (2) to see if the value of the loop condition statement is true or false. If true, execute the third step. If false, the loop statement aborts and the loop is no longer executed.
  3. Execute Loop Body Statement 3
  4. Execute the iteration statement (4) to reassign the loop variable
  5. Re-execute from step 2 again based on the new value of the loop variable

Code Sample

/*
Demand: The highest mountain in the world is Mt. Everest (8844.43 M = 8844430 mm).
If I had a piece of paper large enough, it would be 0.1mm thick. How many times can I fold it to the height of Mt. Everest?
 */
public class Demo09While {
    public static void main(String[] args) {
        //Define a counter with an initial value of 0
        int count = 0;
        //Define paper thickness
        double paper = 0.1;
        //Define the height of Mt. Everest
        int zf = 8844430;
        //Loops are used because they fold over and over, but you don't know how many times they fold, so while loops are better for this situation
        //The folding process stops when the paper thickness is greater than Everest, so the requirement to continue is that the paper thickness is less than Everest height
        while (paper <= zf) {
            //Each time the paper folds during the cycle, the thickness of the paper is doubled
            paper *= 2;
            //Cumulative execution in a loop, corresponding to how many folds
            count++;
        }
        //Print Counter Value
        System.out.println("Need to fold:" + count + "second");
    }
}

do...while loop

Execution process:

  1. Execute the initialization statement (1) to complete the initialization of loop variables;
  2. Execute the loop body statement (2);
  3. Execute the iteration statement (3) and reassign the loop variable;
  4. Execute the loop conditional statement (4) to see if the value of the loop conditional statement is true or false. If true, start again from the second step and execute again based on the new value of the loop variable. If false, the loop statement aborts and the loop is no longer executed.

Code Sample

import java.util.Scanner;

public class Demo10DoWhile {
    public static void main(String[] args) {
    /*
	Enter the password and confirm the password. If the password is identical twice, the registration is successful. If the password is not identical twice, the prompt for re-entry is prompted.
	*/
        Scanner input = new Scanner(System.in);
        String pwdOne = "";
        String pwdTwo = "";
        do {
            System.out.println("Please input a password");
            pwdOne = input.next();
            System.out.println("Please enter a confirmation password");
            pwdTwo = input.next();
            if (!pwdOne.equals(pwdTwo)) {
                System.out.println("Passwords do not match twice, please re-enter");
            }
        } while (!pwdOne.equals(pwdTwo));
        System.out.println("login was successful");
    }
}

Differences among the three looping statements

Analysis from the point of view of number of loops

  • do...while loop executes loop body statement at least once
  • for and while loop precondition statements are valid, and then decide whether to execute the loop body, at least zero times

Analysis from the Life Cycle of Circulating Variables

  • Loop variables declared in for() for loops are not accessible after the loop statement ends;
  • The loop variables of the while and do...while loops can be used again after the while and do...while loops have ended because they are declared outside;

How to choose

  • There is a need to traverse for a significant number of loops (range), select for loop
  • Traversal does not require an obvious number of loops (range), loop while loop
  • If the loop body statement block is executed at least once, consider using a do...while loop
  • Essentially: the three loops can be converted to each other to achieve the function of loops

Three Formats of Dead Loop (Infinite Loop)

Note: Statements that are never accessible cannot be written

loop nesting

Nested loops refer to a cycle in which the body of one loop is another loop. For example, there is a for loop inside a for loop, which is a nested loop. The total number of loops = the number of outer loops * the number of inner loops. Of course, three loops can be arbitrarily nested with each other. Generally, we use the following nested loop format:

 

Execution order

  1. Execute outermost initialization statement
  2. Determine the outermost cycle condition and enter the first cycle if it is satisfied.
  3. Enter the first level of the loop body and encounter the loop statement again. First execute the memory initialization statement, make the second level of loop condition judgment, and then enter the second level of loop body if the judgment condition is met.
  4. If there are more layers of nested circulatory bodies, the above methods can be used to determine whether or not they enter the circulatory body in turn.
  5. After the first internal circulation body operation, the internal circulation body variables are accumulated and the internal circulation body operation is performed again until the conditions for entering the internal circulation body are not met.
  6. Execute the circulatory body operation.
  7. After the first operation of the circulatory system is completed, go back to step 2 to determine if the conditions for entering the circulatory system are met, and if so, repeat the steps until the conditions for entering the circulatory system are not met.
  8. Exit nested loop operation completely.

Code Samples

public class Demo14Test {
    //Print Nine-Nine Multiplication Table
    public static void main(String[] args) {
        // 9 cycles
        for (int a = 1; a <= 9; a++) {
            for (int b = 1; b <= a; b++) {
                System.out.print(a + "*" + b + "=" + (a * b) + "\t"); // t equals a space
            }
            // Line Break
            System.out.println();
        }
    }
}

Jump out of control statement (break continue)

break: can only be used in switch or loop, function: jump out of cycle, end cycle

Code Sample

public class Demo11Break {
    //Keyboard input from the continuous input of integers, input 0 means the end, a total of several positive and negative statistics.
    public static void main(String[] args) {
        java.util.Scanner input = new java.util.Scanner(System.in);

        int positive = 0;
        int negative = 0;
        while (true) {
            System.out.print("Please enter an integer (0) to end:");
            int num = input.nextInt();
            if (num == 0) {
                break;
            } else if (num > 0) {
                positive++;
            } else {
                negative++;
            }
        }
        System.out.println("Positive number:" + positive + ",Negative number:" + negative);
    }
}

Continue:continue can only be used in a loop! Role: Skip this cycle and continue with the next one

Code Samples

public class Demo12Continue {
    public static void main(String[] args) {
        //Print integers between 1 and 100, skipping multiples of 7 and numbers at the end of 7
        for (int i = 1; i <= 100; i++) {
            if (i % 7 == 0 || i % 10 == 7) {
                continue;
            }
            System.out.println(i);
        }
    }
}

We can use the label to jump out of the specified loop

import java.util.Scanner;

public class Demo13Test {
    /*
        Requirements: After the program runs, users can query the corresponding weight loss plan for the week several times until 0 is entered and the program ends.

    */
    public static void main(String[] args) {

        lo:while (true) {
            System.out.println("Please enter the number of weeks you want to view:");
            System.out.println("(If you don't need to continue viewing,Please enter 0 to exit the program)");

            // 1.Keyboard input week data, receive with variable
            Scanner sc = new Scanner(System.in);
            int week = sc.nextInt();
            // 2.Multi-case judgment, implemented with switch statement
            switch (week) {
                // 3.Output corresponding weight loss plans in different case s
                case 0:
                    System.out.println("Thank you for your use");
                    break lo;//Jump out of the loop specified by the label lo
                case 1:
                    System.out.println("Run");
                    break;
                case 2:
                    System.out.println("Swimming");
                    break;
                case 3:
                    System.out.println("Walk slowly");
                    break;
                case 4:
                    System.out.println("Motion bike");
                    break;
                case 5:
                    System.out.println("Boxing");
                    break;
                case 6:
                    System.out.println("Hill climbing");
                    break;
                case 7:
                    System.out.println("Have a good meal");
                    break;
                default:
                    System.out.println("Your input is incorrect");
                    break;
            }
        }


    }
}

Posted by S A N T A on Fri, 01 Oct 2021 09:08:28 -0700