Javase (day05: process control statement)

Posted by sorenchr on Sat, 26 Feb 2022 15:15:52 +0100

if selection structure

1. Classification

  • if single choice structure
  • if double choice structure
  • if multiple selection structure

2. if single choice structure

  • Syntax:
    if (conditional expression){
    }
  • Note: the code in curly braces (code block) will be executed only when the return value of the conditional expression is true

3. if double choice structure

  • Syntax:
    if (conditional expression){
    }
    else {
    }
  • Note: if the double choice structure has and only the code in one code block will be executed (one out of two)
  • Exercise: simulate user login with user name "admin" and password "123456"
Scanner input = new Scanner(System.in);
System.out.print("Please enter user name:");
String userName = input.next();
System.out.print("Please input a password:");
String password = input.next();

if (userName.equals("admin") && password.equals("123456")) {
    System.out.println("Login successful");
}
else {
    System.out.println("Login failed");
}
  • Note: in this exercise, compare the equals method used by the two strings. In the previous study of data types, we learned that using "= =" for basic data types is to compare whether the "data values" are equal, while "= =" for reference data types is to compare whether the "address values" are equal, and the string belongs to reference data types, so use the equals method to compare whether the contents are equal

4. if multiple selection structure

  • Syntax:
    if (conditional expression){
    }else if (conditional expression){
    }else if (conditional expression){
    }......
    else{
    }
  • Note: if there is and only one code block in the multiple choice structure will be executed (one of multiple choices)

5. if selection structure summary

  • If there is only one line of code in the if selection structure, curly braces can be omitted, but it is not recommended for beginners, which will affect the readability of the code
  • When both if single choice structure and if multi choice structure can solve the same problem, it is recommended to use if multi choice structure, because multi choice structure is more efficient
    For example:
// Output the level represented by the score according to the score, int num = 98;
if (num >= 90) {
    System.out.println("excellent");
} else if (num >= 70 && num < 90) {
    System.out.println("good");
} else if (num >= 60 && num < 70) {
    System.out.println("pass");
} else if (num >= 0 && num < 60) {
    System.out.println("fail,");
}
// Multiple selection structure: when num = 98, when the first conditional expression is run, the condition is met, and the output is excellent, then the selection structure will jump out

int num = 98;
if (num >= 90) {
    System.out.println("excellent");
} 
if (num >= 70 && num < 90) {
    System.out.println("good");
} 
if (num >= 60 && num < 70) {
    System.out.println("pass");
}
if (num >= 0 && num < 60) {
    System.out.println("fail,");
}
// Single choice structure, the conditional expression needs to be run once every time, and the execution efficiency is low
  • In the Java language, "{}" is called a code block, while variables defined in the method body and code block are called local variables
    1. Local variable life cycle: when defining a local variable, it is "born" and executed to the end position of braces "death"
    2. Features of code block: variables defined in the code block can only be used in the current scope and cannot be used outside the code block
    3. if selection structure, we also call it "code block with name" or "code block with condition"

  • practice:
    Enter a specific time of hour, minute and second. It is required to print out the next second (24 hours a day). For example, if the input is 23:59:59, the output is 00:00:00; For example, if 17:09:59 is input, 17:10:00 will be output.

2. switch selection structure

  • Syntax:
switch (expression) {
        case Constant 1:
           // When the result of "expression" matches the value of "constant 1", execute the code here.
           break;
        case Constant 2:
           // When the result of "expression" matches the value of "constant 2", execute the code here.
           break;
        case Constant 3:
           // When the result of "expression" matches the value of "constant 3", execute the code here.
           break;
        ......
        default:
                  // When none of the above case s can match successfully, execute the code here.
 }
  • Notes on switch selection structure
    1. Notes on switch

    • The expression results here support byte, short, int, char, String and enumeration, and do not support boolean and floating-point types

    2. Notes on case

    • case can only be followed by constants, not variables, which ensures the security of matching
    • Constant values after case cannot have the same value, otherwise compilation errors will occur
    • The constant data type after case must be consistent with the data type of the return value of the expression. The data type here is consistent, including the type after implicit type conversion

    3. Notes on break

    • Once the break statement is executed, it will jump out of the selection structure and execute the code after the selection structure
    • Break can be omitted. After omission, penetration will occur until the next break is encountered
      For example:
/* 
Requirements: randomly generated [0100]. If the score is: 90 (inclusive) to 100 (inclusive), the output is excellent, 70 (inclusive) to 90 output is good, 60 (inclusive) to 70 output is qualified, and the output below 60 points is unqualified
*/

       // Number of randomly generated [30, 60]
       int num = (int)(Math.random() * 31) + 30;


       System.out.println(num);
       int score = (int)(Math.random() * 101);
       System.out.println("The resulting score is:" + score);

       if (score < 0 || score > 100) {
           System.out.println("Incorrect score input");
       } else {
           switch (score / 10) {
               case 10 :
               case 9 :
                   System.out.println("excellent");
                   break;
               case 8 :
               case 7 :
                   System.out.println("good");
                   break;
               case 6 :
                   System.out.println("pass");
                   break;
               default:
                   System.out.println("unqualified");
           }
       }

In this example, the random method in Math class is used, which can randomly generate a decimal of [0.0, 1.0)

3. Summary of if and switch

  • What switch can do, if can be done; But if can complete the operation, switch may not be able to complete
  • if is often used in "interval judgment", that is, the judgment of boolean type results
  • Switch is often used for "fixed value judgment". Many companies clearly stipulate that switch is used for fixed value judgment, with clear structure

4. for loop structure

  • Syntax:
    for (loop initialization expression; loop condition expression; operation expression after loop){
    Circulatory body;
    }
  • Execution order: loop initialization expression -- > loop condition expression -- > loop body -- > operation expression after loop -- > loop condition expression -- > loop body -- >

5. while loop structure

  • Syntax:
    while (loop condition expression){
    Circulatory body;
    }
  • Execution order: first judge the loop condition expression, and then execute the loop body
  • Note: in the while loop structure, the position of the "operation expression after the loop" has an impact on the result

6,do...while loop structure

  • Syntax:
    do {
    Circulatory body;
    }while (loop condition expression)
  • Execution order: execute the loop body once, and then judge the loop condition expression

7. Frequency of use of three cycles

for loop is the most commonly used, while is the second, do While is rarely used

8. Dead cycle

  • Concept: a cycle that cannot be terminated by its own control

  • classification
    1. Harmful dead cycle

    • Cause: logical confusion or grammatical errors in writing

    2. Favorable dead cycle

    • The simplest dead cycle
// for loop

for (; ; ;) {
}

// While loop while (true){
}

9. break keyword and continue keyword

  • break keyword
    1. Usage: it can be used in switch selection structure and loop structure
    2. Specific functions: use it in switch and jump out of the switch selection structure; Used in the loop structure, jump out of the loop structure and continue to execute the code after the loop structure
  • continue keyword
    1. Usage: it can only be used in circular structure
    2. Specific function: skip one cycle and continue to execute the next cycle
  • Example:
// Han Xin ordered troops. There are two soldiers in a group of three, three in a group of five and four in a group of seven. How many soldiers do you need at least. int i = 1;
while (true) {
    if (i % 3 == 2 && i % 5 == 3 && i % 7 == 4) {
        break;
    }
    i++;
}
System.out.println("Minimum number of people required:" + i);

  • Tagged break and continue
    Because break and continue terminate or skip the nearest loop structure, if you want to terminate or skip the outer loop structure, you can add a label to the outer loop, and then use "break tag name" or "continue tag name" to complete

10. Hypothetical method

// Enter an arbitrary integer to determine whether it is a prime number/*
First, assume that the input number is a prime number, and set a flag by true,When it is judged that the number is not a prime number, the flag Reassign to false
*/
Scanner input = new Scanner(System.in);
System.out.print("Please enter a positive integer:");
int num = input.nextInt();
boolean flag = true;
for (int i = 2; i < num; i++) {
    if (num % i == 0) { 
        flag = false;   
    }
 }
 if (flag) {
    System.out.println(num + "Is a prime number");
 } 
 else {
    System.out.println(num + "Not a prime");
 }


11. Nested loop (difficulty)

It is mainly some exercises. You can use a single loop to solve problems. Try not to use nested loops. The efficiency of nested loops is low

//Print isosceles triangle int count = 5;
for (int i = 0; i < count; i++) {
    for (int j = 1; j <= count-i-1; j++) {
        System.out.print(" "); 
    }    
    for (int k = 1; k <= 2 * i + 1; k++) {
        System.out.print("*");   
    }    
    System.out.println();    
}

Topics: JavaSE