# Day 3: Operator and expression-2. Branch Structure

Source: Internet
Author: User
Tags case statement
1. Operators and expressions-2

1.1. Value assignment

1.1.1. Use "=" for value assignment

"=" Is called the value assignment operator and is used to assign values to variables. In addition to assigning the expression on the right to the left, the value assignment operator has the following features: the value assignment expression also has a value, and its value is the value assigned. The sample code is as follows:

`Int num = 18, index; system. out. println (Index = num % 5); // The result is: 3. The value of the value assignment expression itself also has the value system. out. println (INDEX); // The result is: 3int A, B, C; a = B = c = 100; // C = 100 the value of the entire expression is 100, assign the value to B. Similarly, the value of B = (C = 100) is 100, and then the value is assigned to a, so the value of A is also 100.`

1.1.2. Use an extended value assignment expression

Add other operators before the value assignment operator "=", that is, the extended value assignment operator, which is more efficient than the value assignment operator. We recommend that you use the extended value assignment operator, as shown in-5:

Figure 5

1.2. Character Join Operation

1.2.1. Use "+" for string connection

"+" Not only supports arithmetic operations, but also connects strings and connects strings to other data types ".

When the plus sign acts on two numeric variables, it performs arithmetic operations.

When one of the variables on both sides of the plus sign is a string type, that is, "", it is connected to a string, and the result after the connection is a string type. The sample code is as follows:

`Int A = 100; string MSG = "A =" + A; system. out. println (MSG); // A = 100, String concatenation MSG = "" + 100 + 200; system. out. println (MSG); // The result is: 100200, "+ 100, which is the string 100, and the 200 is 100200msg = 100 + 200 +" "; system. out. println (MSG); // The result is: 300,100 + 200 indicates that the arithmetic operation result is 300, and "300" is added.`

1.3. Conditional (three orders) Operation

1.3.1. Use the condition (three entries) Operator

The conditional operator is also called the "three orders" operator. Its structure is: Boolean expression? Expression 1: expression 2.

The condition operator rules are as follows:

1. Calculate the Boolean expression first;
2. If the value of a Boolean expression is true, the value of the entire expression is the value of expression 1;
3. If the value of a Boolean expression is false, the value of the entire expression is the value of expression 2.

The sample code is as follows:

`Int A = 100, B = 200; int flag = A> B? 1:-1; // because A> B is false, the value of the entire expression is-1, which is assigned to the flag, that is, the flag value is-1.`

1.3.2. Nesting of condition (three object) Operators

Conditional operators can be nested. The so-called nesting refers to the condition (three orders) expression: "Boolean expression? Expression 1: expression 1 or expression 2 in expression 2 is also a condition (three orders) expression, which is equivalent to multiple judgments. The sample code is as follows:

`Int A =-3; string r = a> 0? "Positive": (A = 0? "0": "negative"); system. out. println (r); // The result is a negative number. Because the value of A is smaller than 0, that is, the value of Boolean expression is false, the value of the second expression after the question mark is used as the result of the expression. The second expression after the question mark is also an expression composed of a three-object operator. If expression A = 0 is set to false, the result of the expression is "negative.`

2. Branch Structure

2.1. What is the branch structure?

First, let's look at a requirement. Assume you need to write a cashier's counter collection procedure, which requires you to calculate and output the amount to be receivable and change to zero based on the unit price, quantity purchased, and amount collected.

Through analysis, we can think that this program requires three inputs, namely unit price, quantity, and amount. Defines two outputs, that is, the amount receivable and the value of 0. Because the amount may be decimal, the data structure of the variable is defined as double.

This program can be solved in the following way: the user enters the product unit price, purchase quantity, and collection amount on the console, and then calculates the total price of the product and changes it to zero, and outputs it. The sample code is as follows:

`Public static void main (string [] ARGs) {// define input console = new partition (system. in); system. out. println ("Enter the unit price (￥):"); double unitprice = console. nextdouble (); system. out. println ("Enter quantity:"); double amount = console. nextdouble (); system. out. println ("Enter the amount (￥):"); double money = console. nextdouble (); console. close (); // calculate the total price of the product. Double totalprice = unitprice * amount; // calculate the value of double change = money-totalprice; // output the system. out. println ("the amount to be paid is:" + totalprice + ", and the value is:" + change );}`

As shown in the above Code, after entering the data, you can correctly output the amount to be paid and change to zero. If the demand increases now, you will enjoy a 500 discount when the total price of the product reaches. How can this problem be solved? In this case, the branch structure must be used in software applications.

Any complex program logical structure can be implemented through three basic program structures: "order", "branch", and "loop. -1:

Figure-1

The preceding example shows the sequence structure. Step A is executed, step B is executed, and step 3 is executed. The branch structure is determined based on a condition. If the condition is met, A is executed; otherwise, B is executed. There is also a loop structure to be introduced later. In principle, any complicated program can be solved through these three structures.

When a program needs to run different statements according to different conditions during running, the branch structure can be used. Java has a special syntax structure to implement the branch:

1. Some statements are run when the condition is met. If the condition is not met, these statements are not run -- If structure.
2. Some statements are run when the condition is met; others are run when the condition is not met -- if-else Structure

2.2. If statement

2.2.1. Execution logic of IF Statements

First, let's look at the syntax of the IF statement below:

`Statement 0; If (logical expression) {Statement 1; Statement 2;} Statement 3;`

The procedure for executing the preceding statement is as follows:

Step 1: Execute statement 0;

Step 2: determine the value of a logical expression. The result of this expression is of the boolean type, that is, true or false. This can be a relational expression or a logical expression.

1. If the value is true, the statement in the IF statement block is executed;
2. If the value is false, the IF statement block is skipped;

Step 3: Execute Statement 3.

2.2.2. If statement Flowchart

The execution logic of the IF statement is shown in-2:

Figure 2

When the conditions are met, execute the statement block and then execute the statements below the if statement. Otherwise, skip the statement block and directly execute the statements below the if statement.

2.2.3. If statements are used to process branch Logic

The IF statement is a statement used in Java to process the branch structure. Below, we use the if statement to implement the logic of the Discount Function just now. Let's review the new demand: if the total price of a product is greater than or equal to 500, off. For example, the-3 red part is the if judgment logic:

Figure-3

As you can see, after calculating the total price of a product, you can determine whether the total price is greater than or equal to 500. If the result is true, the amount receivable after the discount is calculated, and then the output is calculated after the change. If the result is false, the system calculates the result and outputs the result after the value is 0. The implementation code is as follows:

`……    double totalPrice = ……；    if (totalPrice >= 500) {         totalPrice = totalPrice * 0.8;    }    ……`

The code above shows that when total> = 500 is true, the total value is multiplied by 0.8, which is off. If total> = 500 is false, the content of the IF statement block is not executed.

2.2.4. Do not omit "{}" in the IF statement Block

When executing an if statement block, you need to pay attention to the following two sections of code:

`Code 1:`
`Int num = 5; If (Num> 2) system. Out. Print (Num); system. Out. println ("greater than 2 ");`

`Code 2:`
`Int num = 5; If (Num> 2) {system. Out. Print (Num); system. Out. println ("greater than 2 ");}`

The analysis of the above two code segments draws the conclusion that the output results of the two code segments are the same, that is, "5 is greater than 2 ". Let's look at the following two pieces of code. Are the output results the same?

`Code 1:`
`Int num = 5; If (Num <2) system. Out. println (Num); system. Out. println ("less than 2 ");`

`Code 2:`
`Int num = 5; If (Num <2) {system. Out. Print (Num); system. Out. println ("less than 2 ");}`

By analyzing the above two code segments, we can conclude that the output result of code segment 1 is "greater than 2", and code segment 2 has no output. The analysis output result shows that the result of code segment 2 is correct, and the "less than 2" output by code segment 1 should not exist. The cause of this problem is, "{}" is not added after the if statement, but the Java syntax stipulates that when the if statement block contains only one statement, "{}" can be omitted. however, the IF statement block can only act on one of the statements below it.

Based on the if judgment of code segment 1 above, it only applies to the first output statement. Because num <2 returns false, the first output statement is not executed, the second output statement "less than 2" does not belong to the scope of if, so it will be executed no matter whether the conditions are met or not. Therefore, the result of "less than 2" is output.

Therefore, considering the readability and scalability of the code, we recommend that you do not omit "{}" even if there is only one statement in the IF statement block.

2.3. If-else statement

2.3.1. Execution logic of IF-else statements

After analyzing the case above, calculate the final amount (before or after the discount), and then calculate the value of 0.

A problem occurs. If the amount collected is smaller than the amount payable, the result of changing the value to 0 will be negative. Obviously, the user experience is poor. Let's make some improvements, consider program exceptions as follows:

1. If the amount received is greater than or equal to the amount receivable, the result is calculated and output after the value is changed;
2. If the amount received is less than the amount payable, an error message is displayed. How can this problem be solved?

In this case, the IF statement alone cannot be solved, because the if statement is used to solve the problem that when a certain condition is met, a certain segment of business processing logic is executed, while the current logic is, when conditions are met, a certain segment of business logic is executed. If conditions are not met, another segment of business logic needs to be executed. See the red part shown in-4:

Figure 4

To implement such judgment logic, consider the IF-else statement. Let's look at the syntax below:

`Statement 0; If (logical expression) {statement Block 1;} else {statement Block 2;} Statement 3;`

The procedure for executing the preceding statement is as follows:

Step 1: Execute statement 0;

Step 2: determine the value of the IF logical expression:

1. If the value is true, statement Block 1 is executed;
2. If the value is false, statement Block 2 is executed;

Step 3: Execute Statement 3.

2.3.2. If-else statement Flowchart

The execution logic of the IF-else statement is shown in-5:

Figure 5

Figure-5 shows that when the condition is met, execute statement Block 1 and then execute the statement below the IF-else statement; otherwise, execute statement Block 2, then execute the statement below the IF-else statement.

2.3.3. The if-else statement is used to process the branch Logic

The following code solves the problem of handling new exceptions:

`...... If (money> = totalprice) {double change = money-totalprice; system. out. println ("the amount to be paid is:" + totalprice + ", and the value is:" + change);} else {system. out. println ("error! The collection amount is less than the amount receivable ");}`

Note: "Money" indicates the amount to be collected, and "totalprice" indicates the amount to be collected. When the amount to be collected is greater than or equal to the amount to be collected, the value is calculated to be zero and output. Otherwise, an error message is displayed.

2.4. Else if statement

2.4.1. nested if-else statement

In daily life, the final result can be obtained without a logical judgment, as shown in-6:

Figure 6

We can see that the process of making a salad has been judged twice. First, we can determine whether there is a cucumber. If there is a cucumber, we can directly make the cucumber salad and end it. If there is no cucumber, we can determine whether there is a carrot, if there is any, make the carrot salad. If not, you cannot end the serving. In this case, if-else alone cannot be implemented, because if-else only judges once and ends, and the current situation needs to be judged twice.

In Java programs, when the number of branches of a program is greater than 2, you can use the IF-else nested method to solve the problem, that is: the else statement block contains the if statement (or the IF-else statement). The following is an actual requirement:

Output level based on the score of the Student:

1. A (score greater than or equal to 90 points );
2. B (score less than 90 points and greater than or equal to 80 points );
3. C (score less than 80 points and greater than or equal to 60 points );
4. D (score less than 60 ).

This program is multi-channel judgment,-7 shows the flowchart:

Figure-7

First, judge whether the score is greater than or equal to 90. If it is true, output A terminates. If it is false, then judge whether the score is greater than or equal to 80. If it is true, output B ends, if it is false, then judge whether the score is greater than or equal to 60. If it is true, Output C is terminated. If it is false, Output D. The analysis shows that the program has been judged three times. Nested judgment is required in else. The Code is as follows:

2.4.2. Else if statement execution Logic

As shown in-8, perform the IF-else judgment again in else:

Figure-8

It can be seen that when there are many layers, the Code definition is not good enough. In actual development, we often use the-9 method. In fact, else if end is a simple method of IF-else nesting:

Figure-9

The code for implementing this program is as follows:

`… … ...if(score>=90) {        System.out.println("A");} else if (score>=80) {        System.out.println("B");} else if(score>=60) {        System.out.println("C");} else {        System.out.println("D");}`

The code above shows that using the else if method, the program logic is clearer and the readability is better.

2.5. Switch-case statement

2.5.1. Switch-case statement execution Logic

Switch-case is a special branch structure, similar to else if, but its application is not as good as else if. It can only be used in special cases, switch-case can be executed from different program entries based on different values of an integer. The syntax is as follows:

`Switch (integer expression) {Case integer constant value 1: // Entry 1 Statement 1; Statement 2; Case integer constant value 2: // entry 2 Statement 3 ;...... Default: // default entry statement N ;}`

The switch-case flowchart is shown in figure-10:

Figure-10

The execution logic is as follows:

Calculate the value of an integer expression:

1. If the value is equal to the integer constant value 1, it is executed from Statement 1, followed by statements 2 and 3 until statement n.
2. If the value is equal to the integer constant value 2, it is executed from Statement 3 until statement n.
3. If no matching value is found, only statement N is executed.

From the analysis, we can see that the switch uses the integer constant value after case as the entry. If the value is equal, the subsequent statement is executed.

When using the switch, pay attention to two issues. First, the constant values after the case must be different. Second, the value of the integer expression after the switch must be of the integer or complex type.

2.5.2. Combined use of switch-case and break

In the preceding code, the value of an integer expression is determined. If the value is equal to a constant value of an integer, all subsequent statements are executed as the entry. However, in practical applications, case1, case2 ,... And Casen correspond to completely different operations, that is, if the expression value is equal to case1, then only the statements after case1 are executed, and the statements after case2 and Casen are no longer executed. In this case, it can be used with the break statement. After the corresponding statement is executed, the switch block is exited and the following statement is not executed. The syntax is as follows:

`Switch (integer expression) {Case integer constant value 1: // Entry 1 Statement 1; Statement 2; break; Case integer constant value 2: // entry 2 Statement 3; break; ...... Default: // default entry statement N ;}`

The break statement in the above program is used to jump out of the switch structure, and its execution logic is as follows:

1. Calculate the value of an integer expression:
2. If the value is equal to the integer constant value 1, Statement 1 and Statement 2 are executed, and the switch structure is exceeded;
3. If the value is equal to the integer constant value 2, Statement 3 is executed and the switch structure is exceeded;
4. If no matching value is found, execute statement n to end. After default, you can leave break unspecified.

2.5.3. The switch-case statement is used for Branch

In practice, the switch-case statement is often used with break. See the following code:

`Int num = 2; Switch (Num) {Case 1: system. out. println ("Call Teaching Department"); break; Case 2: system. out. println ("call Personnel Department"); break; default: system. out. println ("manual service ");}`

The output result of the above code is "Call the Personnel Department", because after matching Case 2, break jumps out of the switch statement.

The switch-case structure is widely used in practical applications. It is often used in conjunction with the break statement to implement the branch function.

In many cases, the switch-case structure can replace the else if structure, while the efficiency of switch-case to implement the branch function is higher than that of the else if structure, and the structure is clearer, so we recommend that you use it. From JDK 7.0, switch-case supports string expressions to facilitate program operations.

Day 3: Operator and expression-2. Branch Structure

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.