Java logic control - sequential structure, branch structure, loop structure

Posted by Christian B. on Fri, 04 Mar 2022 05:55:10 +0100

1: Sequential structure

1.1. The sequence structure is relatively simple Execute line by line in the order in which the code is written

		public class TestDemo {
		    public static void main(String[] args) {
		        System.out.println("aaa");
		        System.out.println("bbb");
		        System.out.println("ccc");
		        //aaa
		        //bbb
		        //ccc
		    }
		}

1.2. If you adjust the writing order of the code, the execution order also changes

		public class TestDemo {
		    public static void main(String[] args) {
		        System.out.println("aaa");
		        System.out.println("ccc");
		        System.out.println("bbb");
		        //aaa
		        //ccc
		        //bbb
		    }
		}

2: Branching structure

2.1 if statement

2.1.1 three forms of basic syntax of if statement
① Basic syntax form of if statement 1
if(Boolean expression){
    //Execute code when conditions are met
}
② Basic syntax form of if statement 2
		if(Boolean expression){
		    //Execute code when conditions are met
		}else{
		    //Execute code when conditions are not met
		}
③ Basic syntax form of if statement 3
		if(Boolean expression){
		    //Execute code when conditions are met
		}else if(Boolean expression){
		    //Execute code when conditions are met
		}else{
		    //Execute code when none of the conditions are met
		}
2.1.2 specific code demonstration of if statement
		public class TestDemo {
		    public static void main(String[] args) {
		        //Determine whether an even number or an odd number
		        int num=10;
		        if(num%2==0) {
		            System.out.println(num + "It's an even number");
		        }else{
		            System.out.println(num+"It's an odd number");
		        }
		    }
		}
		public class TestDemo {
		    public static void main(String[] args) {
		        //Determine whether a number is positive or negative
		        int num = 10;
		        if (num > 0) {
		            System.out.println(num+"Is a positive number");
		        } else if (num < 0) {
		            System.out.println(num+"Is a negative number");
		        } else {
		            System.out.println(num+"Is 0");
		        }
		    }
		}
2.1.3 precautions for if statement
① Drape else problem
		public class TestDemo {
		    public static void main(String[] args) {
		       int x=10;
		       int y=10;
		       if(x==5){
		           if(y==10){
		               System.out.println("LOL");
		           }
		       else{
		               System.out.println("hahaha");
		           }
		       }
		    }
		}

None of the above code will be output because else matches the closest if at this time, but we don't recommend it in actual development.

② Code style issues

In Java, it is more recommended to use: {on the same line as if / else. As shown in the above code

③ Semicolon problem
		public class TestDemo {
		    public static void main(String[] args) {
		        int x = 20;
		        if (x == 10); {
		            System.out.println("hehe");
		        }
		    }
		}

An extra semicolon is written here, resulting in the semicolon becoming the statement body of the if statement, and the code in {} has become a code block irrelevant to an if. Program output hehe

2.2 switch statement

2.2.1 basic syntax of switch statement
		switch(integer|enumeration|character|character string){
		 case Content 1 : {
		 Execute statement when content is satisfied;
		 [break;]
		 }
		 case Content 2 : {
		 Execute statement when content is satisfied;
		 [break;]
		 }
		 ...
		 default:{
		 Execute the statement when the content is not satisfied;
		 [break;]
		 } 
		}
2.2.2 code examples
public class TestDemo {
    public static void main(String[] args) {
        int day=1;
        switch(day){
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Incorrect input");
                break;
        }
    }
}

Depending on the value in switch, the corresponding case statement will be executed. The case statement will end when a break is encountered.
If the value in switch does not have a matching case, the statement in default will be executed.
It is recommended that a switch statement should be accompanied by default.

2.2.3 precautions for switch statement
① Do not omit break, otherwise you will lose the effect of "multi branch selection"
② Note 2 the value in switch can only be integer | enumeration | character | string
③ Note 3 switch cannot express complex conditions
④ Note 4 although switch supports nesting, it is ugly~
// For example, if the value of num is between 10 and 20, print hehe
// Such code is easy to express using if, but cannot be expressed using switch

3: Cyclic structure

3.1 while cycle

3.1.1 basic syntax format of while statement
while(Cycle condition){ 
Circular statement; 
} 

If the loop condition is true, execute the loop statement; Otherwise, end the cycle

3.1.2 code examples
		//Use the while loop to calculate 1+ 2! +  3! +  4! +  5!
        int i=1;
        int sum=0;
        while(i<=5){
            //It is important to reset fac j to 1
            int fac=1;
            int j=1;
            while(j<=i){
                fac*=j;
                j++;
            }
            sum+=fac;
            i++;
        }
        System.out.println(sum);
3.1.3 precautions for while loop statement

① Similar to if, the statement under while can not write {}, but only one statement can be supported when it is not written It is suggested to add {}
② Similar to if, the {suggestion after while is written on the same line as while
③ Do not write multiple semicolons after if, which may lead to incorrect execution of the loop

3.2 for loop

3.1.1 basic syntax of for loop
for(Expression 1;Expression 2;Expression 3){ 
Circulatory body; 
} 

Expression 1: used to initialize loop variables
Expression 2: loop condition
Expression 3: update loop variable
Compared with the while loop, the for loop combines these three parts together and is not easy to miss when writing code

3.1.2 code examples
		//Use the for loop to calculate 1+ 2! +  3! +  4! +  5!
        int i=1;
        int sum=0;
        for(i=1;i<=5;i++){
            int j=1;
            int fac=1;
            for(j=1;j<=i;j++){
                fac*=j;
            }
            sum+=fac;
        }
        System.out.println(sum);
3.1.3 precautions for loop statement

① Similar to if, the statement below for can not write {}, but only one statement can be supported when it is not written It is suggested to add {}
② Similar to if, the {suggestion after for is written on the same line as while
③ Similar to if, do not write more semicolons after for, otherwise the loop may not execute correctly

3.3 do while loop (minor)

3.1.1 basic syntax of do while statement
		do{ 
		Circular statement; 
		}while(Cycle condition);

Execute the loop statement first, and then determine the loop condition

3.1.2 code examples
		//Print 1-10 with do while loop
        int i=1;
        do{
            System.out.println(i);
            i++;
        }while(i<=10);
3.1.3 precautions for do while loop statement

① Don't forget the semicolon at the end of the do while loop
② Generally, do while is rarely used, and for and while are more recommended

3.4 break

The function of break is to end the cycle ahead of time

		//Find the multiple of the first 3 in 100 - 200
        int num = 100;
        while (num <= 200) {
            if (num % 3 == 0) {
                System.out.println("A multiple of 3 was found, by:" + num);
                break;
            }
            num++;
        }

Executing break will end the loop

3.5 continue

The function of continue is to skip this cycle and immediately enter the next cycle

		//Find multiples of all 3 in 100 - 200
        int num = 100;
        while (num <= 200) {
            if (num % 3 != 0) {
                num++; // Don't forget the + + here! Otherwise, there will be a dead cycle
                continue;
            }
            System.out.println("A multiple of 3 was found, by:" + num);
            num++;
        }

When the continue statement is executed, it will immediately enter the next cycle (determine the cycle conditions), so it will not execute the following print statement

Topics: Java