java 具有多个值的切换案例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31161784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:12:41  来源:igfitidea点击:

Switch case with multiple values

javaswitch-statementcase

提问by dsk

Is there something like array of case statement and put it as single case statement into switch- suppose

是否有类似 case 语句数组的东西,并将其作为单个 case 语句放入 switch-假设

String[] statements={"height","HEIGHT"};

and then

接着

switch(code){
 case statements: 
  //code here
  break;
 case something_else:
  break;
}

so if we add values into String array then it will automatically matched from that array in switch? like

因此,如果我们将值添加到 String 数组中,那么它将自动从 switch 中的该数组匹配?喜欢

  var1||var2||whatever //accessed from array or anything else for matching

is there any implementation similar like this?

有没有类似的实现?

采纳答案by Bgvv1983

I think I wouldn't youse a switch in this case. I would do probably something like this

我想在这种情况下我不会使用开关。我可能会做这样的事情

if(Arrays.asList(yourArray).contains(yourValue)){
   //do something
}else{
   //do something else
}

回答by HamoriZ

You can remove the break to get OR

您可以删除中断以获得 OR

switch(code){
 case case1:   
 case case2:
    doSomething();
  break;
}

回答by Eddy

According to the Java Documentation:

根据Java 文档

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).

开关适用于 byte、short、char 和 int 原始数据类型。它还适用于枚举类型(在 Enum 类型中讨论)、String 类和一些包装某些原始类型的特殊类:Character、Byte、Short 和 Integer(在 Numbers 和 Strings 中讨论)。

Unless you can boil your data down to one of these, that's all you can use. You can always break out what you would have in the statement array, but you wouldn't be able to make switch dynamic using an array.

除非您可以将数据归结为其中之一,否则您只能使用这些数据。您总是可以打破语句数组中的内容,但是您将无法使用数组使 switch 动态化。

回答by Codebender

switch case statements don't break unless you specifically ask it to.

除非您特别要求,否则 switch case 语句不会中断。

Hence for your case, you can use this as a work around,

因此,对于您的情况,您可以将其用作解决方法,

switch(code){
 case "height":
 case "HEIGHT": 
 case "weight":
  //code here
  break;
 case something_else:
  break;
}