Two types of branching structures are common in Java:
<1>if statement: Use a Boolean expression or a Boolean type value as a branching condition for branching control.
<2>switch statement: To match multiple shaped values to achieve branch control.
1.if Conditional Statement 1.1 syntax 1.1.1 first form
if (logic expression) {statement ...}
The second form of 1.1.2
if (logic expression) {statement ...} Else {statement ...}
The third form of 1.1.3
if (logic expression) {statement ...} Else if (logic expression) {statement ...} ... // can have 0 or more else if statements Else {statement ...} // The last else= can be omitted
CODE schematic:
The first form of
Package com.oliver.test; Public class iftest { publicstaticvoid main (string[] args) { int age = (int) (Math.random () *80) +1; // [0,79] System.out.println (age); if (age>18) { System.out.println ("The person has grown up"); }}}
The second form of:
Packagecom.oliver.test; Public classIftest { Public Static voidMain (string[] args) {intAge = (int) (Math.random () *80) +1;//[0,79]System.out.println (age); if(age>=18) {System.out.println ("The man has grown up."); } Else{System.out.println ("The person is underage"); } }}
The third form of:
Packagecom.oliver.test; Public classIftest { Public Static voidMain (string[] args) {intAge = (int) (Math.random () *80) +1;//[0,79]System.out.println (age); if(age>20) {System.out.println (Youth); } Else if(age>40) {System.out.println (Middle-aged); } Else if(age>60) {System.out.println (Elderly); } Else{System.out.println (Unknown); } }} 2.switch statements
The Swith statement is a control expression and multiple case labels, and if the difference is that the data type of the control expression after the switch statement can only be byte,short,char,int four integer types, enum type, and java.lang.String type, Cannot be a Boolean type
2.1 Syntax
Switch (expression) { case condition1:{ statement (s) break; } Case condition2:{ statement (s) break; } ... Case conditionn:{ statement (s) break; } default : { statement (s) } }
2.2 Concrete Example schematic
Packagecom.oliver.test; Public classSwitchtest { Public Static voidMain (string[] args) {CharScore = ' B '; Switch(score) { CaseA: {System.out.println (Failed); Break; } CaseB: {System.out.println (Medium); Break; } CaseC: {System.out.println (General); Break; } CaseD: {System.out.println (Poor); Break; } default: {System.out.println ("Input Error"); Break; } } }}
Note: You cannot omit break in the case code block, or it will fall into a trap. (String type is supported in JDK 7)
"Java" JAVA_13 branching structure