如果希望選擇執行若干代碼塊中的一個,你可以使用switch語句:
文法:
switch(n)
{
case 1:
執行代碼塊 1
break
case 2:
執行代碼塊 2
break
default:
如果n即不是1也不是2,則執行此代碼
}
工作原理:switch後面的(n)可以是運算式,也可以(並通常)是變數。然後運算式中的值會與case中的數字作比較,如果與某個case相匹配,那麼其後的代碼就會被執行。break的作用是防止代碼自動執行到下一行。
<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>
另一種情況
<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>
以上是三連網為您介紹的jsp switch語句的用法,希望對您有所協助。