JAVASE Xiaobai study notes (3) flow control statement structure

The flow control statement structure has sequence structure, branch structure and loop structure, See the table below for specific instructions.

Flow control statement structure
Sequence structure: execute sequentially from top to bottom
Branch structure: according to different choices, to execute different codes. if...else and switch...case
Loop structure: Repeated execution of a certain piece of code according to conditions. for, while and do...while

1. Sequence structure

Sequence structure: execute from top to bottom in the same method

package westos.lianxi.zuoye;
/*顺序结构:在同一个方法中代码从上往下依此进行执行.从键盘上输入一个值,并进行打印输出*/
/*实现键盘输入的步骤: 1.导包,格式为:import  java.util.Scanner;
                      导包的位置必须在源文件的上面,在class的上面
                      2.创建键盘录入对象
                      格式为:Scanner sc=new Scanner(System.in);
                      3.通过对象获取数据
                      格式为:int a=sc.nextInt();
 */
import java.util.Scanner;//导包
public class ShunXuJieGou {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("欢迎登陆教务系统");
        //创建键盘录入对象
        Scanner sc=new Scanner(System.in);

        System.out.println("请输入您的姓名:");
        String s=sc.next();
        System.out.println("您的姓名为:"+s);

        System.out.println("请输入您的年龄:");
        int age=sc.nextInt();
        System.out.println("您的年龄为"+age);

        System.out.println("请输入您的分数:");
        double score=sc.nextDouble();
        System.out.println("您的分数为:"+score);

        System.out.println("请告知是否毕业");
        boolean flag=sc.nextBoolean();
        System.out.println("您的毕业情况为:"+flag);
    }
}

The output result is:

欢迎登陆教务系统
请输入您的姓名:
小明
您的姓名为:小明
请输入您的年龄:
18
您的年龄为18
请输入您的分数:
85.5
您的分数为:85.5
请告知是否毕业
true
您的毕业情况为:true

2. Branch structure

2.1 Conditional statement

2.1.1 if single branch statement

if单分支语句的语法格式:
if(条件表达式){
//当条件表达式结果为true时,需要执行的语句块
}

Explanation:
(1) The conditional expression must be a Boolean expression (relational expression or logical expression) or Boolean variable.
(2) When there is only one statement in the statement block, {} can be omitted, but it is recommended to keep it
(3) Execution flow: execute the statement when the condition is established, otherwise it will not be executed

Insert picture description here


2.1.2 if...else double branch conditional statement

if else双分支条件语句的语法格式为:
if(条件表达式){
    
    
//当条件表达式结果为true时,需要执行的语句块1
}else{
    
    
//当条件表达式结果为false时,需要执行的语句块2
}

Explanation:
(1) The conditional expression must be a Boolean expression (relational expression or logical expression), Boolean variable.
(2) When there is only one statement in the if or else statement block, {} can be omitted, but it is recommended to keep
(3) Execution result: execute statement block 1 when the condition is established, execute statement block 2 if it is not established

Insert picture description here


2.1.3 if...else multi-branch conditional statement

if...else多分支条件语句的语法结构:
if(条件表达式1{
    
    
//当条件表达式1结果为true时,需要执行的复合语句1
}else if(条件表达式2{
    
    
//当条件表达式结果为true时,需要执行的复合语句2
...
else{
    
    
//当上述条件表达式结果为false时,需要执行的语句
}

Note:
(1) The {} after each if or else is not necessary, but there is no {}, and only one statement can be taken by default. That is, when there is only one statement in the statement block following if or else, {} can be omitted, but the readability is not good enough.
(2) The last else is not necessary and can be omitted.
(3) Execution process: Judge the condition from top to bottom. Once a certain condition is established, the corresponding statement block will be executed, and the following conditions will not be read. If all conditions are not met, if there is else, then execute else, then execute else, if there is no else, then execute nothing

Insert picture description here

package westos.lianxi.zuoye;

public class DuoFenZhi {
    
    
    public static void main(String[] args) {
    
    
        int score=89;
        //if...else if多分支语句
        if(score>90&&score<=100){
    
    
            System.out.println("成绩优秀");
        }
        else if(score>80&&score<=90){
    
    
            System.out.println("成绩良好");
        }
        else if(score>60&&score<=80){
    
    
            System.out.println("成绩及格");
        }
        else{
    
    
            System.out.println("成绩不及格");
        }
    }

}

The output result is:

成绩良好

2.1.4 Nesting

The if...else series of statements can be nested, and other conditional statements can be nested in any statement block

Implementation features: when the outer conditions are met, the inner conditions are judged


3. Choose the structure

选择结构-switch语法结构:
switch(表达式){
    
    
case 常量值1//执行语句块1
[break;]//break可以省略
case 常量值2//执行语句块2
[break]......
case 常量值n:
//执行语句块n;
[break];
[default:
//执行缺省语句(默认语句)
[break];
]
}

Insert picture description here

Precautions
The result type returned by the expression can only be byte, short, char, int, enumeration (after JDK1.5), String (after JDK1.7)
The type of the result returned by the expression needs to be consistent with the type of the value after the case
The case can only be followed by a constant value, not a variable value or the value of an uncertain expression
In the same switch statement, the constant values ​​of case must be different from each other
Break is optional. When the return result of the expression matches the value after a case, the statement of the corresponding branch is executed. Once a branch is entered, the switch cannot be exited until it encounters a break, otherwise it will continue to execute the next one. case statement (can also be case penetration)
default is optional. The position is not necessarily at the end, and can be any case position. But no matter where it is, it will enter the default branch only after the constant values ​​of all cases do not match, and it will stop only when it encounters the closing bracket "}" of break or switch.

Summary:
1. At the entrance of switch, the expression value matches or does not match a certain case, enters
the exit of 2.switch from default, and ends with the closing bracket "}" of break or switch


4. Conditional judgment and choice of selection structure

1. When the condition judgment is equivalent judgment, and the result of the expression is byte, short, char, int, enumeration, String type, it is more appropriate to use switch, and other conditions are judged
. 2. You can use switch...case Yes, you can definitely use if...else, and return is not necessarily


5. Loop structure

The loop structure is to perform a certain operation repeatedly when certain conditions are met. Three commonly used loop statements are provided in java, namely while loop statement, do...while loop statement and for loop statement.

5.1 while loop statement

while循环语句语法结构:
while(条件表达式){
    
    
//循环体语句块
}

Insert picture description here

Execution process:
(1) First judge the loop condition
(2) The condition is established, execute the loop body statement block
(3) Return to (1)
(4) Know the condition is not established, end the while loop


5.2 do...while loop statement

do while循环语句语法结构:
do{
    
    
//循环体语句块
}while(条件表达式);

Execution process:
(1) First execute the loop body statement block unconditionally
(2) then judge the loop condition
(3) the condition is satisfied, execute the loop body statement block again
(4) back to (2)
(5) until the condition is not satisfied, end do …While loop

Note:
After the loop body is executed once, the condition is judged again. If the condition is established, the next loop body is continued, so the do...while loop executes the loop body at least once

Insert picture description here


5.3 for loop statement

for循环结构语法结构:
for(初始化表达式1;循环条件表达式2;迭代表达式3[
//循环语句块
}

Execution process:
(1) Execute initialization expression 1
(2) Determine loop conditional expression 2
(3) If the condition is satisfied, execute loop body statement block
(4) Execute iteration expression 3
(5) Repeat (2) (3) (4) (5)
(6) Until the loop condition is not established, end the for loop

Insert picture description here

note:

  • Two semicolons are necessary
  • The three expressions can be omitted, but they must be combined with break, otherwise there will be an endless loop
  • Expression 1 can have multiple variable declarations, but they must be of the same type, separated by commas
  • Expression 3 can have multiple variables to update, separated by commas

5.4 Comparison of three loop statements

Insert picture description here

Comparison of three loop statements
The three kinds of loop statements can realize the loop and repeat execution of a certain piece of code, which can be converted into
The execution order is different: for and while are judged first and then executed, do...while are executed first and then judged
The execution effect is different: while and for, if the first condition is not met, the loop body will not be executed once; while do...while executes the loop body once, and then judges the condition to see if the loop body is executed for the second time.
Different execution efficiency: do...while is the most efficient
Each loop has four loop elements, and the for loop reflects the most obvious, loop variable initial value, loop condition, loop body, loop variable update iteration
The for loop is suitable for a clear number of cycles, while do...while is suitable for at least one loop. while is suitable for loop conditions that are relatively clear

5.5 Nested loops

A complete loop structure is nested in a loop body. One loop structure fills the loop body of another loop.
Any other loop structure can be nested in the three loop bodies.

Execution characteristics: execute the outer loop first, execute the outer loop once, and execute the inner loop one round from beginning to end.

Total number of times = number of outer cycles * number of inner cycles. In detail: the total number of times = the number of the first round of the inner loop + the number of the second round of the inner loop + the number of the third inner loop... + the number of the nth round of the inner loop. The number of rounds is the number of outer loops.

Print a rectangle with 4 rows and 5 columns#

(1) Print 4 lines of #

public class QianTao2 {
    
    
    public static void main(String[] args) {
    
    
        for(int i=0;i<4;i++){
    
    
            System.out.println("#####");
        }

    }
}

The output result is:
Insert picture description here
(2) 5 # per line, you can also use loop

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

        }
    }
}

The output result is:
Insert picture description here


5.6 Jump

Jump
break: can only be used in switch or loop, used to jump out of the current loop or switch
continue: can only be used in a loop, end this loop early and continue to the next loop
return: used to end the current method
package westos.lianxi.zuoye;

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

The output result is:
Insert picture description here

package westos.lianxi.zuoye;

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

The result is:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41537102/article/details/109612993