One, switch syntax
is a multi-branch statement that determines which branch to execute by judging the value of an expression
B Reak is used to end a case and then execute a statement other than switch
S witch-switch: case-condition switch determines what happens
Second, switch basic syntax
S Witch (expression) {
C ASE value 1:
Statement 1
B reak;
C ASE value 2:
Statement 2
B reak;
......
C ASE value N:
Statement n
B reak;
D Efault:
Statement
B reak;
}
Third, the matters needing attention
The entire Defaul statement can be dropped, the default statement up to a maximum of one
S Witch (expression), the expression value inside cannot be a floating-point number
Multiple case can execute the same block of statements, the position of case can also be arbitrary
C You must add a break if you have a statement behind your ASE, or you will get a syntax error
C the label behind the ASE can only be a constant or constant expression, with a specific value, not a variable as a label for the case.
Example: in console input 1, print "January", enter 2 print "February", enter 3, print "March", enter other print "Other month"
//switch
Switch(a) {
Case 1:
Console. WriteLine (" January " );
Break;
Case 2:
Console. WriteLine (" February " );
Break;
Case 3:
Console. WriteLine (" March " );
Break;
default:
// to handle the above situation is not satisfied, need to execute the code
Console. WriteLine (" Other months " );
Break
}
Four, the difference between switch and if
I both F and switch are the most common grammars in real-world development.
I the expression value of the F statement is generally of type bool
S Witch statements usually have the execution of a break end Case statement
Exercise: Enter 1-7 from the console to print the corresponding day of the week via switch
Lan Unity Development Foundation--switch Statement Learning Notes