在Java中是否可以编写一个switch语句,其中每个case包含多个值?例如(虽然以下代码显然不起作用):
switch (num) {
case 1 .. 5:
System.out.println("testing case 1 to 5");
break;
case 6 .. 10:
System.out.println("testing case 6 to 10");
break;
}
Run Code Online (Sandbox Code Playgroud)
我认为这可以在Objective C中完成,Java中有类似的东西吗?或者我应该只使用if,else if语句呢?
为了避免嵌套的if语句并提高可读性,我想switch(true){ ... }在Coldfusion中创建一个
语句.我经常在php中使用它,但是当我在Coldfusion中尝试这个时,我在初始化时遇到以下错误:
模板错误
该表达式必须具有常量值.
当switch case在其条件中使用变量时会发生这种情况,例如:
//this example throws the error
switch(true){
case foo == 1:
writeOutput('foo is 1');
break;
}
Run Code Online (Sandbox Code Playgroud)
使用具有常量值的switch(true){...}语句(如错误解释)确实有效:
//this example doesn't throw the error
switch(true){
case 1 == 1:
writeOutput('1 is 1');
break;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法让第一个声明在Coldfusion中工作?也许对变量或某些技巧进行评估,或者这对Coldfusion来说是否明确没有?