一聚教程网:一个值得你收藏的教程网站

热门教程

jsp switch语句的用法

时间:2022-06-29 02:39:29 编辑:袖梨 来源:一聚教程网

如果希望选择执行若干代码块中的一个,你可以使用switch语句:

语法:
switch(n)
   {
   case 1:
     执行代码块 1
     break
   case 2:
     执行代码块 2
     break
   default:
     如果n即不是1也不是2,则执行此代码
   }
工作原理:switch后面的(n)可以是表达式,也可以(并通常)是变量。然后表达式中的值会与case中的数字作比较,如果与某个case相匹配,那么其后的代码就会被执行。break的作用是防止代码自动执行到下一行。


 
    Using the switch Statement
 

 
   

Using the switch Statement


    <%
        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.");
        }
    %>
 


另一种情况


 
    Testing for Multiple Conditions
 

 
   

Testing for Multiple Conditions


    <%
        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!");
        }
    %>
 

热门栏目