具有多个值的开关大小写
Switch case with multiple values
是否有类似 case 语句数组的东西并将其作为单个 case 语句放入 switch-假设
String[] statements={"height","HEIGHT"};
然后
switch(code){
case statements:
//code here
break;
case something_else:
break;
}
所以如果我们将值添加到 String 数组中,那么它会自动从 switch 中的那个数组匹配?喜欢
var1||var2||whatever //accessed from array or anything else for matching
有类似这样的实现吗?
我想我不会在这种情况下使用开关。
我可能会做这样的事情
if(Arrays.asList(yourArray).contains(yourValue)){
//do something
}else{
//do something else
}
除非您特别要求,否则 switch case 语句不会中断。
因此对于您的情况,您可以使用它作为解决方法,
switch(code){
case "height":
case "HEIGHT":
case "weight":
//code here
break;
case something_else:
break;
}
您可以删除中断以获得 OR
switch(code){
case case1:
case case2:
doSomething();
break;
}
A switch works with the byte, short, char, and int primitive data
types. It also works with enumerated types (discussed in Enum Types),
the String class, and a few special classes that wrap certain
primitive types: Character, Byte, Short, and Integer (discussed in
Numbers and Strings).
除非您可以将数据归结为其中之一,否则您只能使用这些数据。你总是可以打破你在语句数组中的内容,但你不能使用数组使开关动态化。
是否有类似 case 语句数组的东西并将其作为单个 case 语句放入 switch-假设
String[] statements={"height","HEIGHT"};
然后
switch(code){
case statements:
//code here
break;
case something_else:
break;
}
所以如果我们将值添加到 String 数组中,那么它会自动从 switch 中的那个数组匹配?喜欢
var1||var2||whatever //accessed from array or anything else for matching
有类似这样的实现吗?
我想我不会在这种情况下使用开关。 我可能会做这样的事情
if(Arrays.asList(yourArray).contains(yourValue)){
//do something
}else{
//do something else
}
除非您特别要求,否则 switch case 语句不会中断。
因此对于您的情况,您可以使用它作为解决方法,
switch(code){
case "height":
case "HEIGHT":
case "weight":
//code here
break;
case something_else:
break;
}
您可以删除中断以获得 OR
switch(code){
case case1:
case case2:
doSomething();
break;
}
A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).
除非您可以将数据归结为其中之一,否则您只能使用这些数据。你总是可以打破你在语句数组中的内容,但你不能使用数组使开关动态化。