The syntax of a switch structure (switching statement)
switch (expression) {---> type int, char
CASE constant 1:---> Casestructure can have multiple
Statement Block 1
break;---> program jump out of the switch structure
CASE constant N: values of---> constants cannot be the same
Statement block N
Break
Default: same as else in---> If structure
Statement block
Break
}
Example 1: Zhang San participates in the computer programming contest and, if obtained first place, will travel for one months. If you get a 2nd place, you will be rewarded with a laptop computer. If you get a third place, you will be rewarded with a mobile phone. Otherwise, there is no reward
1 Public classPractice1 {2 Public Static voidMain (string[] args) {3 intMINGCI = 1;//Rank4 Switch(MINGCI) {5 Case1:6System.out.println ("Travel one months"));7 Break;8 Case2:9SYSTEM.OUT.PRINTLN ("Reward hp notebook PC");Ten Break; One Case3: ASYSTEM.OUT.PRINTLN ("Reward mobile HDD One"); - Break; - default: theSystem.out.println ("No Rewards"); - } - } -}
Switch Selection structure
Operation Result:
1 Public classPractice2 {2 Public Static voidMain (string[] args) {3 intMINGCI = 1;//Rank4 Switch(MINGCI) {5 Case1:6System.out.println ("Travel one months"));7 Case2:8System.out.println ("Reward a laptop");9 Case3:TenSystem.out.println ("Reward a phone"); One default: ASystem.out.println ("No Rewards"); - } - } the}
Practice2
No results were written to break:
Note: If a value is matched but no break is performed, then the statement from the match to that value
At the beginning, each of the following statements executes until the entire program ends or a break is encountered.
Second, switch structure use occasions: int \char 2 types of equivalence judgment to useIii. the similarities and differences between switch structure and if structure
Same point: equal judgment can be achieved
Different points:
1. Different syntax
2. The use of different occasions
2.1 If structure, focusing on range judgments
2.2 Switch structure, focusing on equivalence judgments, types can only be int, char type
3. Efficiency
3.1 In the equivalence judgment, the switch structure efficiency is higher than the IF structure
Iv. exception handling--hasnextint ();
Determines whether an integer
if (Input.hasnextint ()) {//Boolean type
code block
}
Java (4) Switch selection structure