day04_Java process control

Process control statement

In the process of a program execution, the execution order of each statement has a direct impact on the result of the program. Therefore, we must know the execution process of each statement. Moreover, we often need to control the execution order of statements to achieve the functions we want. Process control statements are classified as follows:

  • Sequential structure
  • Branch structure (if, switch)
  • Loop structure (for, while, do... while)

Sequential structure

Sequential structure is the simplest and most basic process control in the program. There is no specific syntax structure. It is executed in sequence according to the sequence of codes. Most codes in the program are executed in this way.

Sequential structure execution flow chart:

Code example

public class Demo {
    public static void main(String[] args) {
        System.out.println(1);
        System.out.println(2);
        System.out.println(3);
        System.out.println(4);
        System.out.println(5);
    }
}

Branching structure

Execute different statements according to different conditions. In Java, the branch structure can be divided into if statement and Switch statement.

if statement format

Format:

Execution process:

  1. First, evaluate the value of the relationship expression
  2. If the value of the relational expression is true, the statement body is executed
  3. If the value of the relational expression is false, the statement body is not executed
  4. Continue to execute the following statements

Execution flow chart

Code example

public class Demo {
    public static void main(String[] args) {
        System.out.println("start");
        int age = 17;
        // If older than 18, You can go to the Internet bar
        if(age >= 18){
            // age > 18 by true Body of statement executed
            System.out.println("You can go to Internet cafes");
        }
        System.out.println("end");
    }
    
}

If... Else of if statement format

Format:

Execution process:

  1. First, evaluate the value of the relationship expression
  2. If the value of the relational expression is true, the statement body 1 is executed
  3. If the value of the relational expression is false, statement body 2 is executed
  4. Continue to execute the following statements

Code example

public class Demo {
    public static void main(String[] args) {
        // The program judges a number, Is it odd or even
        int num = 9;
        
        if(num % 2 == 0){
            System.out.println("even numbers");
        }else{
            System.out.println("Odd number");
        }
    }
}

If... Else in if statement format

format

Execution process:

  1. First, evaluate the value of relationship expression 1
  2. If the value is true, execute statement body 1; If the value is false, the value of relationship expression 2 is evaluated
  3. If the value is true, execute statement body 2; If the value is false, the value of relationship expression 3 is evaluated
  4. ...
  5. If no relational expression is true, the statement body n+1 is executed.

Execution flow chart

Code example

import java.util.Scanner;

/*
Demand: Xiaoming is about to take the final exam. Xiaoming's father told him that he would give him different gifts according to his different test scores
 If you can control Xiao Ming's score, please use the program to realize what kind of gift Xiao Ming should get and output it on the console.
 */
public class Demo {
    public static void main(String[] args) {
        // 1. use Scanner Enter test scores
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter your grade:");
        int score = sc.nextInt();
        // 2. Judge whether the score is within the legal range 0~100
        if (score >= 0 && score <= 100) {
            // Legal achievement
            // 3. In the legal sentence block, judge which reward the score range meets
            if (score >= 95 && score <= 100) {
                System.out.println("A bicycle");
            } else if (score >= 90 && score <= 94) {
                System.out.println("Amusement park once");
            } else if (score >= 80 && score <= 89) {
                System.out.println("Transformers one");
            } else {
                System.out.println("Get beaten up, There is another sad man in this city~");
            }
        } else {
            // Illegal words, Give error prompt
            System.out.println("Your score is entered incorrectly!");
        }
    }

}

matters needing attention:

  • If the statement body controlled by the if statement is a statement, it can be omitted, but it is strongly recommended not to write!

switch statement of branch statement

Format:

In the switch statement, the data type of the expression can be byte, short, int, char, enum (enumeration). String can be received after JDK7.

Execution process:

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

Sample code

import java.util.Scanner;

public class TestSwitch {
    /*
        Demand: enter the number of weeks on the keyboard to display today's weight loss activities.
    
        Monday: running  
        Tuesday: swimming  
        Wednesday: walk slowly  
        Thursday: spinning
        Friday: Boxing  
        Saturday: mountain climbing  
        Sunday: have a good meal 

        analysis:
            1. Enter the week data with the keyboard and receive it with variables
            2. Multi case judgment is realized by switch statement
            3. In different case s, output the corresponding weight loss plan
    */
    public static void main(String[] args){
        // 1. Enter the week data with the keyboard and receive it with variables
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter");
        int week = sc.nextInt();
        // 2. Multi case judgment, using switch Statement implementation
        switch(week){
            // 3. In different case Output the corresponding weight loss plan
            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("Spinning bike");
                break;
            case 5:
                System.out.println("Boxing");
                break;
            case 6:
                System.out.println("Mountain climbing");
                break;
            case 7:
                System.out.println("Have a good meal");
                break;
            default:
                System.out.println("Your input is incorrect");
                break;
        }
    }
}

switch statement case penetration

Overview: if the break statement is omitted from the case in the switch statement, case penetration will begin

Sample code

import java.util.Scanner;

public class Demo {
    /*
        Requirement: enter the number of weeks on the keyboard and output working days and rest days
        (1-5)Working days, (6-7) rest days
        
        
        case How does penetration occur?
        
            If case omits the break statement in the switch statement, case penetration will begin
        
        Phenomenon:
            When case penetration starts, subsequent cases will not have matching effect, and internal statements will be executed
            It will not end until you see the break or finish executing the overall switch statement.

    */
    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("weekdays");
                break;
            case 6:
            case 7:
                System.out.println("Rest Day");
                break;
            default:
                System.out.println("Your input is incorrect");
                break;
        }
    }    
}

Cyclic structure

A loop statement can repeatedly execute a piece of code when the loop conditions are met. This repeatedly executed code is called a loop body statement. When the loop body is repeatedly executed, the loop judgment condition needs to be modified to false at an appropriate time to end the loop, otherwise the loop will be executed all the time and form a dead loop. In general, the composition of the cycle is as follows:

  • Initialization statement: used to indicate the starting state when the loop is opened. In short, it is what it looks like when the loop starts
  • Condition judgment statement: used to indicate the condition of repeated execution of the loop. In short, it is used to judge whether the loop can be executed all the time
  • Loop body statement: used to represent the content of loop repeated execution, which is simply the matter of loop repeated execution
  • Conditional control statement: used to represent the contents of each change in the execution of the loop. In short, it controls whether the loop can be executed

for loop of loop statement

for loop format:

Execution process:

  1. Execute initialization statement
  2. Execute the conditional judgment statement to see whether the result is true or false. If false, the loop ends. If true, continue
  3. Execute loop body statement
  4. Execute conditional control statements
  5. Go back to ② continue

Code example

//Output all "daffodils" on the console. Narcissus number refers to a three digit number. The sum of the number cubes of one digit, ten digit and hundred digit is equal to the original number
public class Demo {
    /*
        Requirement: output all "daffodils" on the console. It is required to print 2 per line
        System.out.print (Print content); Do not wrap after printing
        System.out.println(Print content); Wrap after printing

        analysis:       
            1. Define the variable count, which is used to save the "printed" quantity. The initial value is 0
            2. In the process of determining and printing the number of daffodils, splice spaces without line breaks, and let the count variable + 1 after printing to record the printed quantity
            3. After each count variable + 1, judge whether it reaches the multiple of 2. If yes, wrap the line.

    */
    public static void main(String[] args) {
        // 1. Define variables count,It is used to save the quantity of "printed", and the initial value is 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. In the process of determining and printing the number of daffodils, splice spaces, But do not wrap lines, and let count variable+1,Record the printed quantity
                System.out.print(i + " ");
                count++;
                // 3. Every time count variable+1 After that, judge whether it has reached the multiple of 2. If yes, wrap the line
                if (count % 2 == 0) {
                    System.out.println();
                }
            }
        }
    }
}

Summary: in the future, if the demand has statistics xxx, please think of the counter variable first. The position defined by the counter variable must be outside the loop

while loop of loop statement

  while loop full format

 

while loop execution process:

  1. Execute initialization statement
  2. Execute the conditional judgment statement to see whether the result is true or false. If false, the loop ends. If true, continue
  3. Execute loop body statement
  4. Execute conditional control statements
  5. Go back to ② continue

Sample code

/*
The highest mountain in the world is Mount Everest (8844.43 M = 8844430 mm). If I had a large enough paper,
Its thickness is 0.1 mm. How many times can I fold it to the height of Mount Everest?
 */
public class Demo {
    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;
        //Defines the height of Mount Everest
        int zf = 8844430;
        //Because it needs to be folded repeatedly, it is necessary to use the cycle, but do not know how many times to fold, which is more suitable for use in this case while loop
        //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) {
            //During the execution of the cycle, the thickness of the paper shall be doubled each time the paper is folded
            paper *= 2;
            //How many times is the accumulation performed in the loop folded
            count++;
        }
        //Print counter value
        System.out.println("Folding required:" + count + "second");
    }
}

dowhile loop of loop statement

Full format:

Execution process:

  1. Execute initialization statement
  2. Execute loop body statement
  3. Execute conditional control statements
  4. Execute the conditional judgment statement to see whether the result is true or false. If false, the loop ends. If true, continue
  5. Go back to ② continue

Code example

public class Demo {
    //Requirement: output 5 times on the console"HelloWorld"
    public static void main(String[] args) {
        //do...while Loop implementation
        int j = 1;
        do {
            System.out.println("HelloWorld");
            j++;
        } while (j <= 5);
        
    }
}

The difference between the three cycles

  • for loop and while loop first judge whether the condition is true, and then decide whether to execute the loop body (judge first and then execute)
  • The do...while loop executes the loop body once, and then judges whether the condition is true and whether to continue to execute the loop body (execute first and then judge)

The difference between a for loop and a while loop

  • The self increasing variable controlled by the conditional control statement cannot be accessed again after the for loop ends because it belongs to the syntax structure of the for loop
  • The self increasing variable controlled by the conditional control statement does not belong to its syntax structure for the while loop. After the while loop ends, the variable can continue to be used

Dead cycle

Format:

be careful:   Inaccessible statements cannot be written, otherwise an error will be reported

Jump control statement

Jump control statement (break)

Jump out of the loop and end the loop

public class Demo {
    /*
        break : Terminate execution of loop body content
        Note: use is conditional
                break Statements can only be used in loops and switch es
                
        Demand: simulate working from 20 to 80 and retiring at 60
    */
    public static void main(String[] args){
        for(int i = 20; i <= 80; i++){
            if(i == 60){
                break;        // End the whole cycle
            }
            System.out.println(i + "I'm at work");
        }
    }
    
}

Jump control statement (continue)

Skip this cycle and continue with the next cycle

public class Demo {
    /*
        continue : Skip execution of a loop body
        
        Note: use is based on condition control and is used inside the loop
        
        Demand: simulate the process of elevator ascending, 1-24 floors, 4 floors non-stop
    */
    public static void main(String[] args){
        for(int i = 1; i <= 24; i++){
            if(i == 4){
                continue;
            }
            System.out.println(i + "Here we are~");
        }
    }
    
}

Comprehensive exercise

import java.util.Scanner;
import java.util.Random;

public class Test {
    /*
        Requirements: the program automatically generates a number between 1 and 100. Use the program to guess what the number is?
            When you guess wrong, give corresponding tips according to different situations
            If the guessed number is larger than the real number, it indicates that the guessed data is larger
            If the guessed number is smaller than the real number, it indicates that the guessed data is smaller
            If the number you guessed is equal to the real number, you will be prompted to congratulate you on your correct guess
        
        1. Prepare Random and Scanner objects for generating Random numbers and keyboard entry respectively
        2. Use Random to generate a number between 1 and 100 as the number to guess
        3. Enter the data guessed by the user with the keyboard
        4. Use the entered data (the data guessed by the user) and random number (the data to be guessed) to compare and give a prompt
        
        5. The above contents need to be carried out many times, but it is impossible to predict how many times the user inputs. You can guess correctly and use the while(true) dead loop package
        6. After you guess right, break ends

    */
    public static void main(String[] args){
        // 1. prepare Random and Scanner object, It is used for generating random numbers and keyboard entry respectively
        Random r = new Random();
        Scanner sc = new Scanner(System.in);
        // 2. use Random Generate a 1-100 Number between, As the number to guess
        int randomNum = r.nextInt(100) + 1;
        
        // 5. The above contents need to be repeated, However, it is impossible to predict how many times the user enters, and you can guess correctly, use while(true)Dead circulation package
        while(true){
            // 3. Enter the data guessed by the user with the keyboard
            System.out.println("Please enter the data you guessed:");
            int num = sc.nextInt();
            // 4. Use the entered data(User guessed data)Random number(Data to guess)Compare, And give tips
            if(num > randomNum){
                System.out.println("Guess big");
            }else if(num < randomNum){
                System.out.println("Guess it's small");
            }else{
                // 6. After you guessed right, break end.
                System.out.println("congratulations,You guessed right");
                break;
            }
        }
        
        System.out.println("Thank you for your use");
        
    }
}

Posted by cedricm on Mon, 29 Nov 2021 05:21:44 -0800