如果希望选择执行若干代码块中的一个,你可以使用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语句的用法,希望对您有所帮助。