|
Switch
- One of the three branching
mechanisms in Java (other ?if and if else statements)
- implements branching - one
of a number of different branches is executed
- each branch statement starts
with the word case, followed by a constant called a case label, followed
by a colon, and then a sequence of statements (see general formula
below)
- there can also be a section
labeled default (optional, usually placed last)
it can be used to output an error message
How it works
- when the controlling
expression is evaluated, the code for the case label whose value matches
the controlling expression is executed
- if no case label matches,
then the only statements executed are those following the default label
- the switch statement ends
when it executes a break statement, or when the end of the switch
statement is reached
- when the computer executes
the statements after a case label, it continues until a break statement
is reached
- if the break statement is
omitted, then after executing the code for one case, the computer will
go on to execute the code for the next case
General Formula
Switch (Controlling_Expression)
//choice of which branch to execute is determined by
the controlling expression
//must evaluate to char or int
{
case Case_Label_1;
Statement_Sequence_1
Break;
//break statement
case Case_Label_2;
Statement_Sequence_2
Break;
case Case_Label_n;
Statement_Sequence_n
Break;
//each case label must be same type as controlling
expression
//each case label must only appear once
Default:
Default_Statement Sequence
Break;
}
Example
public swExample ()
{
int day = IBIO.inputInt ("Enter a number between 1 and 7 >>");
System.out.print ("That day of the week is : ");
switch (day)
{
case 1:
System.out.println ("Sunday");
break;
case 2:
System.out.println ("Monday");
break;
case 3:
System.out.println ("Tuesday");
break;
case 4:
System.out.println ("Wednesday");
break;
case 5:
System.out.println ("Thursday");
break;
case 6:
System.out.println ("Friday");
break;
case 7:
System.out.println ("Saturday");
break;
}
}
|