Choose structure: if you love, please love deeply

Posted by foevah on Sun, 02 Jan 2022 19:41:46 +0100

Select structure

Hello, welcome back. I'm Peng Peng! HAKUNA MATATA!!!

On the basis of data and operation, there is a new demand: process control. Generally, the code execution process will not be executed in the end. Many times, the appropriate direction will be selected according to the changes of data, and even the running results of the program will be changed. Starting from this lesson, I will introduce you to the process control structure of Java language, including selection structure and loop structure.

The result of the program is closely related to the execution order of the code. By using some specific statements to control the execution order of the code, we can complete specific functions, which is the process control structure. In fact, the process control of Java program is not only the selection structure and loop structure, but also a default structure, called sequential structure, that is, the code structure in which the program executes from top to bottom and from left to right according to the code order. The sequential structure is the simplest process control structure and does not require specific control statements. Most codes of the program are executed in this way:

This structure is too simple to spend space on.

This course introduces the selection structure, and the next course introduces the circular structure.

Selection structure is also called judgment structure / branch structure, that is, select the corresponding branch to execute according to whether the judgment condition is true. Therefore, the selection structure is generally composed of two parts: judgment conditions and branches. There may be multiple judgment conditions and branches. Execute the corresponding branches according to different conditions to complete complex business logic. Through this course, you will be able to:

Use the if statement to control the execution flow of your Java program

Use the switch statement to control the execution flow of your Java program

Use the Scanner object to enter data in the console

The course contents are as follows:

  • If statement: if you love, please love deeply
  • Scanner scanner: I'm a data explorer
  • switch statement: sit in rows and eat fruits

The first if statement: if you love, please love deeply

1.1 concept and if format of selection structure

To select a structure, first judge whether the condition is true. If the condition is true, execute part of the code. If not, execute another part or end the code. Therefore, selecting a structure is also called a judgment structure. Judgment conditions are generally one or more relational expressions. Of course, complex logical expressions are not excluded, because their execution results are boolean values.

Look at a piece of code:

public class Test{
    public static void main(String[] args) {
        System.out.println("Start execution");
        // Define two variables of type int, both of which have a value of 10
        int a = 10;
        int b = 10;
    
        if (a == b) { // To judge whether two variables are equal, it is obvious that the condition is true
            // If you can go here, the conditions are true
            System.out.println("a and b Is equal");
        }
        System.out.println("End execution");
    }
}

Some tips are printed at the beginning and end of this code, and the middle is what we pay attention to. The keyword if is followed by a pair of parentheses, which is a relational expression, Then followed by a pair of braces (curly braces), which is the basic format of the if statement. It means that if the return result of the relational expression in the braces after the if is true, the code in the braces will be executed - the code enclosed by a pair of braces is called a code block, otherwise, the code in the braces will be skipped and the final output statement will be executed directly "End execution". Obviously, a == b is true, so the output of this code is:

Start execution
a and b Is equal
 End execution

On the contrary, if a == b is changed to such a condition a > b, the judgment condition will not hold,

public class Test{
    public static void main(String[] args) {
        System.out.println("Start execution");
        // Define two variables of type int, both of which have a value of 10
        int a = 10;
        int b = 10;

        if (a > b) { // To judge whether two variables are equal, it is obvious that the condition is true
            // If you can go here, the conditions are true
            System.out.println("a and b Is equal");
        }
        System.out.println("End execution");
    }
}

The execution result becomes:

Start execution
 End execution

The following two conclusions can be drawn from the running effect of the above code. First, the basic format of the if statement is:

     // First format:
    if (Relational expression) {
        // Statement body
    }

Second, its execution process:

That is, when the return result of the relational expression is true, the statement body in the if code block will be executed. Otherwise, the program will skip the if statement and directly execute to the end. This is the simplest if statement format, which represents the execution logic of "If then".

Test 1: if statement use

Look at the program and say the result:

public class Test{
    public static void main(String[] args) {
        int x = 1, y = 1;
        if (x++ == 2 && ++y == 2) {
            x = 7;
        }
        System.out.println("x = " + x + ", y = " + y);
    }
}    

Answer: x = 2, y = 1

1.2 if and else formats

If you love, please love deeply, otherwise, please let go. If the conditions are not established, it does not mean that the procedure must end. How to implement such a structure? Look at another code:

public class Test{
    public static void main(String[] args) {
        System.out.println("Start execution");
        // Define two variables of type int, both of which have a value of 10
        int a = 10;
        int b = 10;
    
        if (a == b) { // If love
            System.out.println("Please love deeply");
        } else { // otherwise
            System.out.println("Please let go");
        }
        System.out.println("End execution");
    }
}

After the code block of the if statement, I added an else code block. At this time, the condition of a == b is true, and "please love" will be printed, but the content of else code block will not be output.

Start execution
 Please love deeply
 End execution

Else code block is not executed. Now, we do the same, or change the judgment condition to: a > b, so the condition is not tenable. Will the else code block execute? Look at the output:

public class Test{
    public static void main(String[] args) {
        System.out.println("Start execution");
        // Define two variables of type int, both of which have a value of 10
        int a = 10;
        int b = 10;
    
        if (a > b) { // If love
            System.out.println("Please love deeply");
        } else { // otherwise
            System.out.println("Please let go");
        }
        System.out.println("End execution");
    }
}
Start execution
 Please let go
 End execution

Bingo! if code block and else code block are mutually exclusive. I found a treasure!

Yes, if and else here form a complete selection structure. They can only execute one branch, and they can never execute two parts at the same time. Then, according to the above code, we get the second format of if statement and its execution process:

    // Second format:
    if (Relational expression) {
        // Statement body 1
    } else {
        // Statement body 2
    }

Execution process:

If the result returned by the relational expression of the if statement is true, execute the code block immediately after the if, that is, "statement body 1". Otherwise, execute the code block after else, that is, "statement body 2". Finally, the program ends. This is the second format of the if statement, which represents the execution logic of "if - then - otherwise".

"Looking at this rhythm, it seems that the if statement has not been introduced yet..."

"You are so clever."

1.3 else if format

Artificial intelligence is so popular that we have also developed an intelligent robot "Xiaohei classmate". Xiao Hei is smart and polite. Whenever you talk to her, she will say hello to you according to the present time. For example, if it is between 0-12 o'clock, she will say "good morning" to you, and between 13-18 o'clock, she will say "good afternoon". If it is between 18-24 o'clock, she will say "good evening". If you casually tell her a time that is not in these ranges, she will be angry! If you don't believe it, try it:

public class Test{
    public static void main(String[] args) {
        // Define variables to record the current time
        int time = 18; 

        // Xiao Hei greets you according to your time
        if (time >= 0 && time <= 12 ) { 
            System.out.println("Xiao Hei said: Good morning");
        } else if (time >= 13 && time <= 18) {
            System.out.println("Xiao Hei said: Good afternoon");
        } else if (time >= 19 && time <= 24) {
            System.out.println("Xiao Hei said: Good evening");
        } else {
            // If you say the time is too casual, people will be angry!
            System.out.println("Xiao Hei said: Is it cold, I don't know this time!");
        }
    }
}

Output results:

Xiao Hei said: Good afternoon

If has seen it, else has seen it, but else if has not seen it. It looks very tall!

The literal meaning of else if is "otherwise, if", that is, when the previous if condition does not hold, look at the condition behind the else if. If it does not hold, continue to look for the subsequent else if condition. If any if or else if is judged to be true, the code inside will be executed, and then the whole if selection structure will jump out. Otherwise, Until all the judgments are not tenable, the code block after the last else will be executed, such as changing the value of the variable time to - 1 or 25,

public class Test{
    public static void main(String[] args) {
        // Define variables to record the current time
        int time = -1; 

        // Xiao Hei greets you according to your time
        if (time >= 0 && time <= 12 ) { 
            System.out.println("Xiao Hei said: Good morning");
        } else if (time >= 13 && time <= 18) {
            System.out.println("Xiao Hei said: Good afternoon");
        } else if (time >= 19 && time <= 24) {
            System.out.println("Xiao Hei said: Good evening");
        } else {
            // If you say the time is too casual, people will be angry!
            System.out.println("Xiao Hei said: Is it cold, I don't know this time!");
        }
    }
}

The execution result becomes:

Xiao Hei said: Is it cold, I don't know this time!

For other time ranges (0-24), this code will output the corresponding words.

The above code uses the third format of the if statement:

    // Third format:
    if (Relationship expression 1) {
        // Statement body 1
    } else if (Relational expression 2) {
     // Statement body 2
    }  // ...
    else {
      // Statement body n+1
    }

This format seems a little complicated, but it is not difficult to understand. In the previous figure, it is easier to understand the execution process of this format:

I'll write down the meaning of this flowchart so that you can understand it by comparison:

Execution process:
    First judge the relationship expression 1, See if it works(true:establish, false:Not established).
     establish,   Then execute statement body 1,
     Not established, Then judge relationship expression 2, See if it works.
         establish, Execute statement body 2,
         Not established, Then judge relationship expression 3, See if it works.
 ...
 By analogy, judge all conditions, if the relationship expression n establish, The body of the statement is executed n, 

    Otherwise, execute the body of the statement n + 1

It must be noted that no matter how many conditions there are in the whole structure of the if statement, each condition is a parallel relationship. They can only execute one of them or the last else branch. In addition, through various formats of if statements, it is found that except the first if judgment condition, other else if and else code blocks can be omitted. They are "non essential". Whether you want to use so many conditions and else branches when writing code depends entirely on your mood.

In addition, sometimes the judgment condition of the if statement or the code block after else is very simple - there is only one line of code. At this time, the braces can be omitted:

public static void main(String[] args) {
    if (5 > 3) // You can omit braces when there is only one line of code in the code block, but it is not recommended
        System.out.println("5 Greater than 3 established");
    else 
        System.out.println("5 Greater than 3 does not hold");
}

Although this can be done from the perspective of syntax, experienced developers do not recommend us to do so, because new content may be added to the code block at any time. If you forget to add braces, it will be a disaster.

Test 1: if statement use

1. Requirement: given two variables, use the if statement to judge the larger value and output the corresponding information:

    int a = 3, b = 5;

answer:

public class Test{  
    public static void main(String[] args) {
        int a = 3, b = 5;
        if (a > b) {
            System.out.println("a greater than b");
        } else if (a == b) {
            System.out.println("a be equal to b");
        } else {
            System.out.println("a less than b");
        }
    }
}

2. Demand: output the corresponding level according to the student's score

  • 90-100 Emperor
  • Prime Minister 80-90
  • 70-80 ministers
  • 60-70 county officials
  • Grass people below 60

answer:

public class Test{ 
    public static void main(String[] args) {
        int score = 83;   // Define student achievement

        // According to the student's performance, compare with the conditions set in the question, and output as required
        if (score >= 90 && score <= 100) {
            System.out.println("emperor");
        } else if (score >= 80 && score < 90) {
            System.out.println("Prime Minister");
        } else if (score >= 70 && score < 80) {
            System.out.println("minister");
        } else if (score >= 60 && score < 70) {
            System.out.println("county magistrate");
        } else if (score >= 0 && score < 60) {
            System.out.println("Grass people");
        } else { // Pay attention to the processing of illegal data
            System.out.println("There is no such achievement, Are you from Mars?");
        }
    }
}

The second level Scanner: I'm a data explorer

The data in actual development, such as user login information, order status, etc., are almost obtained dynamically, rather than directly defined as a fixed value in the above code: int score = 83;. Although we can't get data directly like the production environment, the Java language provides us with a tool for simulation: scanner. Scanner is a scanner that can scan the data we enter on the console. Therefore, we can simulate the effect of dynamic data acquisition through it.

So, how to use Scanner?

Scanner is a class in the Java language (the concept of class is described in detail in the [object-oriented] Chapter). You can regard it as a tool with certain functions. Its function is to receive the data entered from the console and then hand over these data to the program for processing. Using scanner to enter data on the console requires three steps:

Step 1: guide the package. Actually, it imports the scanner class

    import java.util.Scanner; // Import the scanner class

Step 2: create scanner object. The scanner class needs to work as an object

    // The name of the scanner object is sc. you can also define other names according to the naming rules of identifiers, such as scanner, next, etc
    Scanner sc = new Scanner(System.in);

Step 3: receive data. Use object Method name () is used to get the data we entered and assign the result to a variable.

    int a = sc.nextInt();

Write a piece of code to try the effect:

// 1. Guide Package
import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        // 2. Create a keyboard entry object
        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter an integer: "); // Add a hint
        // 3. Receive data
        int i = sc.nextInt();

        // Print the data entered by the user to the console
        System.out.println("i: " + i);
    }
}

The three steps of using Scanner are indispensable. The first and second steps are in a fixed format. Except that the Scanner name sc can be changed to your favorite identifier, other codes cannot be changed. In particular, pay attention to the location of the package guide code in the first step: above the class, and the second and third steps are in the main method.

When the program reaches the third step, the console will display the flashing cursor. At this time, the program is waiting for us to enter data (the whole program is blocked):

At this point, we can use the keyboard to enter data. The question is: what data can we enter? The nextInt() method means "get an integer of type int from the console", so we can enter a number and try:

Soon, the console reprinted the number 10 we entered. What happened in this process? Return to the above code: when we enter 10 on the console and press enter, the nextInt() method scans the data and assigns it to variable i. then, the output statement prints out the value of variable i again. This is the use of Scanner.

Returning to the above case of "outputting the corresponding level according to the student's score", now we can enter the student's score from the console. After receiving the data, we can use the if statement to judge: sf

// 1. Guide Package
import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        // 2. Create a keyboard entry object
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter an integer: ");
        // 3. Receive data
        int score = sc.nextInt(); // Enter the student's grade
        // According to the student's performance, compare with the conditions set in the question, and output as required
        if (score >= 90 && score <= 100) {
            System.out.println("emperor");
        } else if (score >= 80 && score < 90) {
            System.out.println("Prime Minister");
        } else if (score >= 70 && score < 80) {
            System.out.println("minister");
        } else if (score >= 60 && score < 70) {
            System.out.println("county magistrate");
        } else if (score >= 0 && score < 60) {
            System.out.println("Grass people");
        } else { // Pay attention to the processing of illegal data
            System.out.println("There is no such achievement, Are you from Mars?");
        }
    }
}

You might say that student grades are not necessarily integers?! Yes, how to enter floating point numbers? Also, can I enter what I want to say from the console?

The answer is yes. The eight basic data types of the Java language learned earlier, except for the char type, have corresponding receiving methods. If you want to receive char type data, you can use an int type variable to receive it, and then force the type to be converted to char type; If you want to accept your confession of love for me, you need to use String type, because it may be a small composition of more than 10000 words:

nextByte(): receive byte type data. Usage example: byte by = sc.nextByte();

nextShort(): receive data of type short. Usage example: short sh = sc.nextShort();

nextInt(): receive data of type int. Usage example: int i = sc.nextInt();

nextLong(): receive long type data. Usage example: long lo = sc.nextLong();

nextFloat(): receive data of type float. Usage example: float fl = sc.nextFloat();

nextDouble(): receive data of type double. Usage example: double dou = sc.nextDouble();

nextBoolean(): receive data of boolean type. Usage example: boolean bo = sc.nextBoolean();

nextLine(): receive String type data. Usage example: String line = sc.nextLine();

Finally, it should also be noted that when the data type entered on the console does not match the expected type of the method used by the scanner object, the program will report an error. For example, the line sc.nextInt() expects the int type. If we enter a string, it will turn into this result:

The program reported an error and terminated. Although we can't understand most of the error messages, we can probably know the problem of "input mismatch" through the literal meaning of the line of inputmismatch Exception. To be exact, the program throws an Exception and terminates. The name of the Exception is inputmismatch Exception. The last line of the Exception information indicates that there is a problem in line 12 of our code: int i = sc.nextInt();, The meaning is very clear, that is, there is a type mismatch when entering data. At this stage, you are not required to know more about the concept of "Exception". You only need to know that the error reported by the program is caused by the inconsistency between the input type and the type required by the scanner method, and try to avoid such a situation.

Test 1: Scanner scanner usage

1. Requirements: write code, enter two integers on the keyboard, and sum them

Steps to realize keyboard entry function:

Step 1: guide the package.

Step 2: create scanner object.

Step 3: receive data.

answer:

// 1. Guide Package
import java.util.Scanner;
public class Test {
    public static void main(String[] args) {
        // Requirements: enter two integers on the keyboard to sum them
        // 2. Create a keyboard entry object
        Scanner sc = new Scanner(System.in);

        // 3. Prompt the user to enter data and receive it
        System.out.println("Please enter the first integer: ");
        int a = sc.nextInt();
        System.out.println("Please enter the second integer: ");
        int b = sc.nextInt();

        // 4. Calculate the sum of integers
        int sum = a + b;

        // 5. Print results
        System.out.println("sum: " + sum);
    }
}

2. Requirements: enter two data on the keyboard to obtain the larger value of the two data

Train of thought analysis:

A: three steps of keyboard entry:

Guide package; Create a keyboard entry object; Obtain data;

B: get the larger value of two data: format 2 implementation of if statement

C: output larger results

answer:

import java.util.Scanner;

public class IfDemo {
    public static void main(String[] args) {
        // Requirement: enter two data on the keyboard to obtain the maximum value of the two data
        // 1. Create a keyboard entry object to receive the data entered by the user (including: guide package, create object)
        Scanner sc = new Scanner(System.in);

        // 2. Prompt the user to enter two integers and receive them
        System.out.println("Please enter the first integer: ");
        int a = sc.nextInt();
        System.out.println("Please enter the second integer: ");
        int b = sc.nextInt();

        // 3. Define variables and record the maximum value
        int max;

        // 4. Judge the maximum value of two integers through the second format of if statement
        if (a >= b) {
            // If you go here, it means a is big
            max = a;
        } else {
            // If you go here, b is big
            max = b;
        }

        // 5. Print the results to the console
        System.out.println("The larger value is: " + max);
    }
}

The third switch statement: sit in rows and eat fruits

The if statement can be applied to almost all development scenarios. However, when the judgment conditions of each branch are specific values, using the if statement is not as intuitive as using the switch statement. For example, to judge the week corresponding to an integer of 1-7, use the if statement and the switch statement respectively:

Let's first look at the effect of the if statement:

public class Test{
    public static void main(String[] args) {
        int weekDay = 1;
        if (weekDay == 1) {
            System.out.println("Monday");
        } else if (weekDay == 2) {
            System.out.println("Tuesday");
        } else if (weekDay == 3) {
            System.out.println("Wednesday");
        } else if (weekDay == 4) {
            System.out.println("Thursday");
        } else if (weekDay == 5) {
            System.out.println("Friday");
        } else if (weekDay == 6) {
            System.out.println("Saturday");
        } else if (weekDay == 7) {
            System.out.println("Sunday");
        } else {
            System.out.println("I don't know such a time, Are you from Mars?");
        }
    }
}

Let's look at the effect of using the switch statement:

public class Test{    
    public static void main(String[] args) {
        int weekDay = 1;
        switch (weekDay) {
           case 1:
               System.out.println("Monday");
               break;
           case 2:
               System.out.println("Tuesday");
               break;
           case 3:
               System.out.println("Wednesday");
               break;
           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("I don't know such a time, Are you from Mars?");
               break;
       }
    }
}

This is the standard format of switch statements. The functions of the two pieces of code are completely equivalent. Carefully observe that when using the switch statement, it is easier to observe the specific value of the judgment condition and the clear structure of the whole code, which is also the reason why the switch statement appears. In the actual development, all switch structures can be replaced by if structures, and vice versa. Remember: switch is only applicable to judging the branch structure of specific values, not to judging a certain range, but if can. The execution process of this code is almost the same as the if structure:

Look back and compare the if statement to see the format of the switch statement and the meaning of each part:

    switch (expression)  {   // Value types of expressions: byte, short, int, char, jdk5 can be enumeration; After JDK7, it can be String
        case Value 1:       // Case is followed by the value to be compared with the expression, and each case represents a branch
            Statement body 1;     // The statement body part can be one or more statements
            break;      // It means to interrupt and end. You can end the switch statement
        case Value 2:
            Statement body 2;
            break;
            // ...      //  There can be many case s
        default:        // It means that when all conditions do not match, the content here is executed, which is equivalent to the else part of the if statement
            Statement body n+1;
            break;
    }

The switch keyword is equivalent to the if keyword, except that the parentheses behind if are relational expressions, while the parentheses behind switch are generally a variable, and the value of the variable is compared with the value of each subsequent case branch, that is, the "comparison" action is postponed. Since the "expression" after switch is a variable, what data type is it? Can all types be used? The answer is No. As mentioned earlier, switch is suitable for judging fixed values, which means that these values must be known. In other words, these values should be constants, For example, literal constants (byte, short, char, int), String, enumeration and other types. Each data of String type is a String constant, so it can be used as the expression type of switch (a new feature of JDK7); enumeration is a constant class supported by java language by default, so it can also be used as the expression type of switch (new features of JDK5). Among the eight basic data types of Java language, boolean, long, float and double are not supported temporarily, mainly because there are too few scenarios for branch selection of these types of data as conditions, but the possibility of providing corresponding support in subsequent JDK versions is not ruled out.

Case represents each specific branch, followed by a specific value. The value here is actually the possible value of the previous "expression" variable. If the matching is successful, execute the statement body in this case. Otherwise, continue to judge the next case until any case is successfully matched, or execute the default part. The default branch is equivalent to the last else of the if structure. The statement body can have multiple sentences. Just like the code block behind the if, the business logic can be complex or simple.

There is usually a break statement at the end of each case to represent the end of this branch. Its function is similar to the code block end tag of if structure. When the program executes the break statement, it will jump out of the whole switch structure. Similarly, just as the curly braces of an IF statement can be omitted, the break statement is not necessary. There are two differences: first, the if statement can omit the curly braces only when there is only one line of statements in the contemporary code block, while the case branch does not have this restriction. It can omit the break statement on the premise of having a lot of code; Second, in the if statement, the code after executing the branch will jump out of the if structure. If the break statement in the case is omitted, the switch will not jump out after executing the current branch, but continue to execute the subsequent case or default branches until the break statement jumps out or all the remaining code of the switch structure is executed. This is applicable to scenarios where multiple values execute the same business logic. For example, chestnuts:

Demand: enter the number from January to December and output the corresponding season. If the input is wrong, a prompt message will be printed

Spring: 3, 4, 5;

Summer: 6, 7, 8;

Autumn: 9, 10, 11;

Winter: 12, 1, 2;

Full code:

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter month (1)-12): ");
        int month = sc.nextInt();
        switch (month) {
            case 3: // This branch has nothing and no break statement. The same below
            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;
            case 12:
            case 1:
            case 2:
                System.out.println("winter");
                break;
            default:
                System.out.println("Are you talking about Mars moon?");
                break;
        }
    }
}

In this code, when the value of the case branch is 3, 4, 6, 7, 9, 10, 12, 1 and other numbers, there is no code or break statement. How does the program execute? When we input the number 3 from the console and match the first case branch successfully, we will execute the code in the branch - although there is nothing, after executing the branch, because there is no break statement, the program will not jump out of the switch structure, but will continue to execute the code of subsequent branches, which comes to the line of case 4:, Does the code need to make another judgment now? The answer is: No. It's like holding a key and opening a door of the warehouse. After entering, the whole warehouse's gold, silver and jewelry appear in front of you and let you take it at will. Will you go out and enter another door? The following diagram may help you understand the execution flow of this Code:

The whole switch is a warehouse. Each case branch is a door to enter the warehouse, the default branch is a back door, and the expression is the key to open the door. If the value of the expression matches any door, you can open the door to enter the warehouse, and then gold, silver and jewelry can be made by you. Therefore, after matching case 3: successfully, since the break statement is not executed, continue to execute case 4 and case 5 branches until the break statement of case 5 is encountered and exit the switch structure.

The second half of the switch statement is a little difficult. You need to read this knowledge carefully and run these codes to understand it.

Test 1: use of switch statement

1. Look at the procedure and say the result:

public static void main(String[] args) {
    int x = 2, y = 3;
    switch (x) {
        default:
            y++;
        case 3:
            y++;
            break;
        case 4:
            y++;
    }
    System.out.println("y=" + y);
}

Answer: y=5

2. Implement a simple calculator, which supports four functions: addition, subtraction, multiplication and division.

For example, enter the numbers 3 and 5, and the sum result is 8. (tip: the null constant of the default value of String type is null, which can be used to judge whether the String variable is re assigned)

Console data format:

Please enter the first number:

​ 3

Please enter the second number:

​ 5

Please enter your operation by serial number (1 plus; 2 minus; 3 times; 4 divide):

​ 1

The result of 3 + 5 is 8

answer:

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the first number:");
        int num1 = sc.nextInt();
        System.out.println("Please enter the second number:");
        int num2 = sc.nextInt();
        System.out.println("Please enter your operation by serial number (1 plus; 2 minus; 3 times; 4 divide):");
        int opr = sc.nextInt();

        int result = 0;
        String operate = null; // The default value of string type. If it is re assigned later, it indicates that the correct operator is executed
        switch (opr) {
            case 1:
                result = num1 + num2;
                operate = " + ";
                break;
            case 2:
                result = num1 - num2;
                operate = " - ";
                break;
            case 3:
                result = num1 * num2;
                operate = " * ";
                break;
            case 4:
                result = num1 / num2;
                operate = " / ";
                break;
            default:
                System.out.println("Input error, unsupported operator:" + opr);
                break;
        }
        if (operate != null) { // It is used to judge that any case code has been executed normally instead of default
            System.out.println(num1 + operate + num2 + " The results are:" + result);
        }
    }
}

Course summary

Finally, make a summary of the content of this lesson:

  • Three formats of if statements and their execution processes:
     // First format:
    if (Relational expression) {
        // Statement body
    }

    // Second format:
    if (Relational expression) {
        // Statement body 1
    } else {
        // Statement body 2
    }

    // Third format:
    if (Relationship expression 1) {
        // Statement body 1
    } else if (Relational expression 2) {
        // Statement body 2
    }  // ...
    else {
        // Statement body n+1
    }
  • Standard format and execution process of switch statement:
    switch (expression)  {   // Value types of expressions: byte, short, int, char, jdk5 can be enumeration; After JDK7, it can be String
        case Value 1:       // Case is followed by the value to be compared with the expression, and each case represents a branch
            Statement body 1;     // The statement body part can be one or more statements
            break;      // It means to interrupt and end. You can end the switch statement
        case Value 2:
            Statement body 2;
            break;
            // ...      //  There can be many case s
        default:        // It means that when all conditions do not match, the content here is executed, which is equivalent to the else part of the if statement
            Statement body n+1;
            break;
    }
  • if statement is suitable for interval value / range judgment, while switch is suitable for fixed value judgment;
  • All values to be judged by the switch statement are constants, and the initialization has been completed when the code of the switch structure is loaded, so the switch efficiency is higher;
  • When writing programs, data testing should be done to test several situations: correct data, error data and boundary data.

Topics: Java Back-end Programmer