在我使用任何编程语言的1个月经验中,我假设switch
case
条件将接受括号中的任何内容作为布尔检查thingamajig,即
这些:
|| && < >
知道我的意思吗?
类似
char someChar = 'w';
switch (someChar) {
case ('W' ||'w'):
System.out.println ("W or w");
}
可悲的是,似乎没有这样的方式。我不能在switch case中进行布尔检查。
有办法吗?
顺便说一下,如果我听起来很混乱,非常抱歉。我还不太清楚这种语言的所有名称:X
任何答案赞赏
答案 0 :(得分:47)
你可以为这样的案件实现OR:
switch (someChsr) {
case 'w':
case 'W':
// some code for 'w' or 'W'
break;
case 'x': // etc
}
案例就像是“goto”,多个gotos可以共享同一行开始执行。
答案 1 :(得分:6)
你可以做 -
switch(c) {
case 'W':
case 'w': //your code which will satisfy both cases
break;
// ....
}
答案 2 :(得分:3)
每个案件通常都会出现“休息”;声明指示执行应终止的位置。如果省略“break;”,则执行将继续。您可以使用它来支持多个应该以相同方式处理的情况:
char someChar = 'w';
{
case 'W':
// no break here
case 'w':
System.out.println ("W or w");
break;
}
答案 3 :(得分:1)
切换案例是用于给定表达式的替代评估的分支。表达式在switch括号中给出,可以是byte,short,char和int数据类型。
switch语句的主体称为switch switch。一份声明 在开关块中可以用一个或多个case或default来标记 标签。 switch语句计算其表达式,然后执行 匹配案例标签后面的所有陈述。
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
答案 4 :(得分:0)
对于切换语句的替代方法(条件时多次),我认为最好的解决方案是使用枚举。例如:考虑以下情况: -
public enum EnumExample {
OPTION1{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the first option.");
return void;
}
},
OPTION2{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the second option.");
return void;
}
},
OPTION3{
public double execute() {
Log.info(CLASS_NAME, "execute", "The is the third option.");
return void;
};
public static final String CLASS_NAME = Indicator.class.getName();
public abstract void execute();
}
上述枚举可以按以下方式使用:
EnumExample.OPTION1.execute();
希望这可以帮助你们。