if
-
Concept: if statement can control the execution process of the program according to a certain condition
-
Basic if structure syntax:
If (Boolean expression){ / / execute when the Boolean expression is true, otherwise it will not be executed }
Example:
int a = 10; //If a < 100 is true, execute the code in {}. After execution, jump out of the if structure and continue to execute other codes downward if( a < 100 ){ System.out.println("Hello"); } System.out.println("The program is over!");
-
if--else structure syntax:
If (Boolean expression){ / / execute when Boolean expression is true }else{ / / execute when Boolean expression is false }
Example:
//Receive two integers from the console and calculate the quotient of the two integers //1. Create Scanner Scanner sc = new Scanner(System.in); System.out.println("Please enter two integers:"); //2. Select the method of receiving data int a = sc.nextInt(); int b = sc.nextInt(); //Calculates the quotient of two integers //If B= Execute a/b when 0, otherwise the prompt divisor cannot be 0! if( b!=0 ){ //b!= Execute when 0 is true System.out.println( a/b ); }else{ //b!= Execute when 0 is false System.out.println("Divisor cannot be 0!"); }
-
If else if else is mainly used for multi condition filtering syntax:
if( Boolean expression 1 ){ //Executes when Boolean expression 1 is true }else if(Boolean expression 2){ //Executes when Boolean expression 2 is true }else if(Boolean expression 3){ //Executes when Boolean expression 3 is true }...else{ //The above expressions are all false }
Example:
//A Mercedes Benz will be rewarded for more than 85 //70-84 reward Chang'an for running //60-69 reward one electric donkey //If the score is lower than 60, Foxconn will be rewarded with one offer import java.util.Scanner; public class TestIf3{ public static void main(String[] args){ //The user enters a score and prints the reward corresponding to the score Scanner sc = new Scanner(System.in); System.out.println("Please enter a grade:"); int s = sc.nextInt(); //The same value executes different codes according to different conditions //A Mercedes Benz will be rewarded for more than 85 if( s>=85 ){ System.out.println("Reward a Mercedes Benz!"); }else if( s>=70 && s<=84 ){ //70-84 reward Changan for running System.out.println("Reward Chang'an for running!"); }else if(s>=60 && s<=69){ //60-69 reward one electric donkey System.out.println("Reward an electric donkey!"); }else{ //If the score is lower than 60, Foxconn will be rewarded with one offer System.out.println("Reward Foxconn offer One!"); } } }
Execution process:
When the program executes, judge whether the conditions in if -- else if are met in turn. When a condition is found to be met, execute the code in {} and then jump out of the if -- else if structure. If there is no if else if statement that meets the condition, execute the last else {}
The relationship between natural language and code
What if -- > if() {} If so, otherwise -- > if(){}else {} What if, what if How else? ---- > if () {} else if () {} else {}
Supplement to if statement
When there is only one line of code to be executed in the if statement, the {} sign can be omitted, which is applicable to all structures if / if -- else / if -- else if else The only line of code in the short form of if (a) cannot be used to define variables
4, switch
In this example, the case 1: statement in the internal switch statement does not conflict with the case 1: statement in the external switch statement. The variable count is only compared with the outer case statement. If the variable count is 1, the variable target is compared with the inner case statement.
Here we can find the following points:
This last point is particularly interesting because it shows us how the Java compiler works. When compiling a switch statement, the Java compiler will check each case constant and create a "jump table", which will be used to select the execution path based on the expression value. Therefore, if you need to choose between a set of values, the switch statement will be much faster than the equivalent if else statement.
The compiler can do this because it knows that case constants are of the same type. All it has to do is compare it with the switch expression to see if it is equal. The compiler does not have this capability for a series of if expressions.
-
Function: it is applicable to equivalence judgment and execute different codes according to different values of variables
-
Syntax:
switch( variable ){ case Value 1://Execute when the value of the variable is equal to the value 1; case Value 2://Execute when the value of the variable is equal to the value 2; case Value 3://Execute when the value of the variable is equal to the value 3; //... default://Execute when there is no value matching the variable; }
-
Execution process:
When the program finds that the variable is the same as a certain value, execute the code behind the case. After execution, continue to execute other codes downward regardless of whether it matches the subsequent case until the last line of code is executed. (failure mechanism)
-
Break keyword: when the program encounters the break keyword, it will jump out of the switch structure. Usually, switch is used together with break. Example:
import java.util.Scanner; public class TestSwitch2{ public static void main(String[]args){ Scanner sc = new Scanner(System.in); System.out.println("Please enter the ranking:"); //User input ranking -- print the substitute name of ranking int n = sc.nextInt(); //1 --- champion //2 --- runner up //3 --- third place //4 --- Dianjun //5~n-- please keep working hard switch( n ){ case 1 : System.out.println("champion");break; case 2 : System.out.println("runner-up");break; case 3 : System.out.println("Runner up");break; case 4 : System.out.println("rearguard");break; default: System.out.println("Please keep trying!"); } } }
be careful:
Variables in switch support byte, short, int and char String is supported after JDK7 After JDK12, switch can generate a result After JDK13, you can print the results generated by the switch statement in the print statement (preview version) The final version is confirmed after JDK14
-
Nested switch statements
You can use a switch statement as part of the statement sequence of an external switch statement, which is called a nested switch statement. Because a switch statement defines its own block, the case constants of external switch statements and internal switch statements will not conflict. For example, the following program segment is completely correct:public static void main(String[] args) { switch (count) { case 1: switch (target) { case 0: System.out.println("target is zero"); break; case 1: System.out.println("target is one"); break; } break; case 2: // ... } }
- The difference between switch statement and if statement is that switch statement can only test equality, while if statement can evaluate any type of Boolean expression. That is, the switch statement can only find a value between case constants that matches the value of the expression.
- There are no two identical case constants in the same switch statement. Of course, the case constant in the external switch statement can be the same as the case constant in the internal switch statement.
- switch statements are generally more effective than a series of nested if statements.
Difference between if statement and switch statement
Both if and switch statements represent conditional statements, which can be distinguished from efficiency and practicability.
1. Distinguish from efficiency
In terms of efficiency, when making conditional judgment on different values of the same variable, you can use either switch statement or if statement. Using switch statements is more efficient, especially the more branches to judge, the more obvious.
2. Distinguish from practicality
From the perspective of statement practicability, switch statement is not as good as if conditional statement. If statement is the most widely used and practical statement.
3. When to use if statement and switch statement
In the process of program development, when to use if statement and switch statement needs to be determined according to the actual situation, and we should try to make the best use of everything. Switch statements cannot be used all the time because of their high efficiency, nor can switch statements be used because if statements are often used. It is necessary to analyze the specific problems according to the actual situation and use the most suitable conditional statements.
In general, if conditional statements can be used for those with few judgment conditions, but switch statements are best used in the implementation of some multi condition judgments