If you want to execute one of several code blocks, you can use the switch statement:
Syntax:
Switch (n)
{
Case 1:
Execution code block 1
Break
Case 2:
Execution code block 2
Break
Default:
If n is neither 1 nor 2, execute this code
}
Working principle: the (n) behind the switch can be an expression or (and usually) a variable. Then, the value in the expression is compared with the number in case. If it matches a case, the subsequent code is executed. Break is used to prevent the code from being automatically executed to the next line.
<HTML>
<HEAD>
<TITLE> Using the switch Statement </TITLE>
</HEAD>
<BODY>
<H1> Using the switch Statement </H1>
<%
Int day = 3;
Switch (day ){
Case 0:
Out. println ("It's Sunday .");
Break;
Case 1:
Out. println ("It's Monday .");
Break;
Case 2:
Out. println ("It's Tuesday .");
Break;
Case 3:
Out. println ("It's Wednesday .");
Break;
Case 4:
Out. println ("It's Thursday .");
Break;
Case 5:
Out. println ("It's Friday .");
Break;
Default:
Out. println ("It must be Saturday .");
}
%>
</BODY>
</HTML>
Another situation
<HTML>
<HEAD>
<TITLE> Testing for Multiple Conditions </TITLE>
</HEAD>
<BODY>
<H1> Testing for Multiple Conditions </H1>
<%
Int temperature = 64;
Switch (temperature ){
Case 60:
Case 61:
Case 62:
Out. println ("Sorry, too cold! ");
Break;
Case 63:
Case 64:
Case 65:
Out. println ("Pretty cool .");
Break;
Case 66:
Case 67:
Case 68:
Case 69:
Out. println ("Nice! ");
Break;
Case 70:
Case 71:
Case 72:
Case 73:
Case 74:
Case 75:
Out. println ("Fairly warm .");
Break;
Default:
Out. println ("Too hot! ");
}
%>
</BODY>
</HTML>