Branch and loop statements

Posted by Valera on Tue, 22 Feb 2022 13:55:34 +0100

Branch statement

Process control

Classification: sequential structure, branch structure (if, switch), circular structure (while, do... While, for)

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.

Branch statement

if statement

    Format:
    if(Relational expression){
    Sentence body;
    }

Execution process:
① First, evaluate the value of the relationship expression
② If the value of the relational expression is true, the statement body is executed
③ If the value of the relational expression is false, the statement body is not executed
④ Continue to execute the following statements
Example:
Judge whether the two values are equal. If they are equal, output: a is equal to b

  public static void main(String[] args) {
        int a=1;
        int b=1;
        if (a==b){
            System.out.println("a be equal to b");
        }
    }
​```java

if... else statement

Format:
if(Relational expression){
Statement body 1;
}else{
 Statement body 2;
};

Execution process:
① First, evaluate the value of the relationship expression
② If the value of the relationship expression is true, execute statement body 1
③ If the value of the relationship expression is false, execute statement body 2
④ Continue to execute the following statements

Example:
Demand: judge whether a is greater than b. If yes, the value of a in the control output is greater than b. if not, the value of a in the console output is not greater than b

public static void main(String[] args) {
        int a=3;
        int b=1;
        if (a>b){
            System.out.println("a greater than b");
        }else{
            System.out.println("a Not greater than b");
        }
    }

Result: a is greater than b

Requirement: if an integer is given arbitrarily, please use the program to judge whether the integer is odd or even, and output whether the integer is odd or even on the console.

 public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        System.out.print("Please enter a number:");
        int num=scanner.nextInt();
        if (num%2==0){
            System.out.println(num+"It's an even number");
        }else{
            System.out.println(num+"It's an odd number");
        }

    }

if... else... if statement

Format:
if(Relationship expression 1){
Statement body 1;
}else if(Relational expression 2){
 Statement body 2;
}
...
else{
Statement body n;
}

Execution process:
① First, evaluate the value of relationship expression 1
② If the value is true, execute statement body 1; If the value is false, calculate the value of relationship expression 2 ③ if the value is true, execute statement body 2; If the value is false, the value of relationship expression 3 is evaluated
④...
⑤ If no relational expression is true, the statement body n+1 is executed.
Example:
Requirement: enter a week number (1, 2,... 7) on the keyboard and output the corresponding Monday, Tuesday,... Sunday

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter the number 1-7: ");
        int num = scanner.nextInt();
        if (num == 1) {
            System.out.println("Today is Monday");
        } else if (num == 2) {
            System.out.println("Today is Tuesday");
        } else if (num == 3) {
            System.out.println("Today is Wednesday");
        } else if (num == 4) {
            System.out.println("Today is Thursday");
        } else if (num == 5) {
            System.out.println("Today is Friday");
        } else if (num == 6) {
            System.out.println("Today is Saturday");
        } else if (num == 7) {
            System.out.println("Today is Sunday");
        } else {
            System.out.println("Your input is incorrect.");
        }

    }

Demand: Xiaoming is about to take the final exam. Xiaoming's father told him that he will give him different gifts according to his different test scores. If you can control Xiaoming's score (full score 100), please use the program to realize what kind of gift Xiaoming should get and output it on the console.

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter your grade:");
        double num = scanner.nextDouble();
        if (num == 100) {
            System.out.print("You are the best");
        } else if (num < 100 && num >= 90) {
            System.out.print("Very good");
        } else if (num < 90 && num >= 75) {
            System.out.print("So-so:");
        } else if (num < 75 && num >= 60) {
            System.out.print("A little poor");
        } else {
            System.out.print("Very bad");
        }
    }

switch Statements

    Format:
    switch(expression){
        case Value 1:
            Statement body 1;
            break;
        case Value 2:
            Statement body 2;
            break;
        ......
        default:
            Statement body n;
            [break;]
         }

Format Description:
Expression: the values are byte, short, int and char. After JDK5, it can be enumeration, and after JDK7, it can be String.
case: followed by the value to be compared with the expression.
The meaning of "switch" is to end the switch.
default: indicates that when all conditions do not match, the content of this area will be executed, which is similar to else of i statement.

Execution process:
① First, evaluate the value of the expression.
② Compare with the value after case in turn. If there is a corresponding value, the corresponding statement will be executed. In the process of execution, it will end when it encounters brealk.
③ If the value after all case s does not match the value of the expression, the statement body in default will be executed, and then the program will end.
Example: enter 1-7 to display the day of the week.

    Scanner scanner = new Scanner(System.in);
    int num = scanner.nextInt();
    switch (num) {
        case 1:
            System.out.println("Today is Monday");
            break;
        case 2:
            System.out.println("Today is Tuesday");
            break;
        case 3:
            System.out.println("Today is Wednesday");
            break;
        case 4:
            System.out.println("Today is Thursday");
            break;
        case 5:
            System.out.println("Today is Friday");
            break;
        case 6:
            System.out.println("Today is Saturday");
            break;
        default:
            System.out.println("Today is Sunday");
            break;
    }

Demand: there are 12 months in a year, which belong to four seasons: spring, summer, autumn and winter. Enter a month with the keyboard. Please use the program to judge which season the month belongs to and output it.
Spring: 3, 4, 5
Summer: 6, 7, 8
Autumn: 9, 10, 11
Winter: 1, 2, 12

        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        switch (num) {
            case 3:
            case 4:
            case 5:
                System.out.println("spring");
                break;
            case 6:
            case 7:
            case 8:
                System.out.println("summer");
                break;
            case 9:
            case 10:
            case 11:
                System.out.println("autumn");
                break;
            default:
                System.out.println("winter");
                break;
        }

Cyclic structure

Composition of circulation structure:
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 indicate the content of loop repeated execution, which is simply the matter of loop repeated execution
 Conditional control statement: used to indicate the contents of each change in the execution of the loop. In short, it controls whether the loop can be executed

Syntax corresponding to loop structure:
Initialization statement: here can be one or more statements, which can complete some initialization operations
 Conditional judgment statement: a result value of boolean Type, which can determine whether to execute the loop body. For example: a-3
 Loop statement: here can be any statement. These statements will be executed repeatedly
 Conditional control statement: here, a statement is usually used to change the value of the variable, so as to control whether the loop continues to execute downward. common i++,i--Such operation

while statement

    while(Boolean expression){
    Logic code (loop operation);
    }

Execution process:
First judge the Boolean expression, and if the result is true, execute the logical code.
After this execution, judge again, and if the result is still true, execute the logic code again.
Until the result of Boolean expression is false, the loop structure will be exited and subsequent code will be executed.

Example:
Requirement: print "helloworld" for 10 times

        int i=1;
        while (i<11){
            System.out.println(i+"hello world");
            i++;
        }
    while If no condition is added to the loop, it will become an dead loop
    For the first time, there are entry conditions, which are judged first and then implemented. It is applicable to the case where the cycle coefficient is clear

Example:
Demand: calculate the sum of 1 + 2 + 3 +... + 99 + 100

public class Main {
	public static void main(String[] args) {
	int i = 1;
        int num = 0;
        while (i < 101) {
            num = num + i;
            i++;
        }
        System.out.println(num);
	}
}

Result: 5050

Demand: calculate the sum of all even numbers between 1-100.

public class Main {
	public static void main(String[] args) {
	int i = 0;
        int num = 0;
        while (i < 101) {
            num = num + i;
            i = i + 2;
        }
        System.out.println(num);
	}
}

Result: 2550

do... while statement

Format:
    do{
        Logic code(Cyclic operation);
        }wuile(Boolean expression);

Execution process:
First perform a loop operation, and then judge the Boolean expression.
If the result is true, the loop operation is performed again.
If the result is false, the loop structure will exit and subsequent code will be executed.

Example:
Requirement: print "helloworld" for 10 times

public static void main(String[] args) {
        int i = 0;
        do {
            System.out.println(i + "hello world");
            i++;
        } while (i < 10);
    }

Requirements: check the completion of students' homework, input teachers' comments, and decide whether students need to copy the code.

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        char answer = 'o';
        do {
            System.out.println("Students copy their homework!");
            System.out.println("Teacher approval.");
            answer = scanner.next().charAt(0);
        } while (answer != 'y');
        System.out.println("Don't copy.");
    }

for statement

    Format:
    for(Initialization statement;Conditional judgment statement;Conditional control statement){
        Loop body statement;
    }

Execution process:
① Execute initialization statement
② Execute the conditional judgment statement to see whether the result is true or false. If false, the loop ends. If true, continue to execute
③ Execute loop body statement
④ Execute conditional control statement
⑤ Go back to ② continue

Example:
Requirement: output HelloWorld 5 times on the console

        for (int i=0;i<5;i++){
            System.out.println("HelloWorld");
        }

Demand: there are 5 students in one class. Please input the scores of 5 students through the console and calculate the average score.

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double num = 0;
        double sum=0;
        for (int i = 1; i <= 5; i++) {
            System.out.print("Please enter page"+i+"Student achievement:");
            num=scanner.nextDouble();
            sum=sum+num;
        }
        System.out.println("average:"+sum/5);
    }

Process control

break

Program running encountered break The operation ends.

Example:
The console will input the scores of 5 students. If any student's scores produce illegal data (not meeting the number between 0 and 100), it will directly exit the integration cycle operation

       public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double num = 0;
        double sum = 0;
        boolean flag = true;
        for (int i = 1; i <= 5; i++) {
            System.out.print("Please enter page" + i + "Student achievement:");
            num = scanner.nextDouble();
            if (num < 0 || num > 100) {
                System.out.println("Input error, the program ends.");
                flag = false;
                break;
            }
            sum = sum + num;
        }
        if (flag == true) {
            System.out.println("average:" + sum / 5);
        }
    }

Continue

continue Is to end this cycle and enter the next cycle

Example:
Demand: calculate the sum of all even numbers between 1-100

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

Nested loop

    Concept: in a complete loop structure, another complete loop structure is nested.

Demand: output 9 * and there are three in each row and column.

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (j == 2) {
                    System.out.println("*");
                    continue;
                }
                System.out.print("*");
            }
        }
    }

Demand: calculate the average score of 5 students in 3 classes.

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double num = 0;
        double count = 0;
        for (int j = 1; j <= 3; j++) {
            System.out.println("The first" + j + "Class student information:");

            for (int i = 1; i < 6; i++) {
                System.out.print("Please enter page" + j + "Class, No" + i + "Student achievement:");
                num = scanner.nextDouble();
                count = count + num;
            }
            System.out.println("The first" + j + "Average score of class:" + count / 5);
            count = 0;
        }
    }

Requirements: print right triangle

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < i; j++) {
                System.out.print("*");
            }
            System.out.println();
           continue;
        }
    }

Requirement: print 99 multiplication table

    public static void main(String[] args) {
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + "*" + i + "=" + i * j + "\t\t");
            }
            System.out.println();
        }
    }

summary

·Concept of cycle:
    ·Execute a piece of logic code repeatedly through a certain condition.
·while Cycle:
    ·while(){}
·do while Cycle:
    ·do{}while;
·for Cycle:
    ·for(Initial; Conditions; Iteration (operation)}
·Process control Keywords:
    ·break,continue
·Nested loop:
    ·In a complete loop structure, another complete loop structure is nested.

Topics: Java JavaEE