First, the principle is to explain the problem:
switch (expression)
{
case constant Expression 1: statement 1;
....
Case constant Expression 2: statement 2;
Default: statement;
}
1.default is that if you do not have a matching case, default is not required.
The statement after 2.case can be used without curly braces.
the judging condition of 3.switch statement can accept int,byte,char,short,string,enum other types cannot be accepted.
4. Once the case is matched, the subsequent program code is executed sequentially, regardless of whether the following case matches, until a break is encountered, which allows several case to execute a unified statement.
Principle of the principle, here are a few easy to confuse examples.
1. Standard type (the break statement is followed by case)
int i=3;
Switch (i)
{
Case 1:
SYSTEM.OUT.PRINTLN (1);
Break
Case 2:
SYSTEM.OUT.PRINTLN (2);
Break
Case 3:
SYSTEM.OUT.PRINTLN (3);
Break
Default
SYSTEM.OUT.PRINTLN ("Default");
Break
}
Output Result:
3
2. Special Type 1 (not completely break statement, can complete some special applications)
int year=2005;
int month=3;
int day;
Switch (month)
{
Case 1:
Case 3:
Case 5:
Case 7:
Case 8:
Case 10:
Case 12:
day=31;
Break
Case 2:
day=28;
Break
Case 4:
Case 6:
Case 9:
Case 11:
day=30;
Break
}
Here day=31;
3. Special type 2 (default position)
int i=1;
Switch (i)
{
Case 1:
SYSTEM.OUT.PRINTLN (1);
Default
SYSTEM.OUT.PRINTLN ("Default");
Case 2:
SYSTEM.OUT.PRINTLN (2);
Break
Case 3:
SYSTEM.OUT.PRINTLN (3);
Break
}
Output Result:
1
Default
2
Java Switch-case