在java中对字符串使用或运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18475508/
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-08-12 01:57:02  来源:igfitidea点击:

using or operator on String in java

java

提问by Dip

I want to check a string with a multiple values using or operator , is that possible ?

我想使用 or 运算符检查具有多个值的字符串,这可能吗?

like if(str.equals("A" || "B" || "C")){
//do this 
}
else if(str.equals("D" || "E" || "F")){
//do that
}

I am getting error while compiling, that || can not be used in string

编译时出错, || 不能在字符串中使用

采纳答案by arshajii

You can also use a switchin Java 7:

您还可以switch在 Java 7 中使用 a :

switch (str) {
case "A":
case "B":
case "C":
    // do this
    break;
case "D":
case "E":
case "F":
    // do that
    break;
}

This might be more readable if you have many strings you want to compare against. For reference, see the "Using Strings in switch Statements" section of the switchStatementtutorial.

如果您有许多要比较的字符串,这可能更具可读性。如需参考,请参阅switchStatement教程的“在 switch 语句中使用字符串”部分。

回答by Josh M

if(str.equals("A") || str.equals("B") || str.equals("C")){ .... }

if(str.equals("A") || str.equals("B") || str.equals("C")){ .... }

You have to separate your conditions.

你必须分开你的条件。

回答by dasblinkenlight

You do not need an ORin this case: you can write the same condition like this:

OR在这种情况下,您不需要 an :您可以像这样编写相同的条件:

if (Arrays.asList("A", "B", "C").contains(str)) {
    ...
}

This test is successful when the test string stris contained in the list specified in the call to asList, which conveniently takes a variable number of parameters.

当测试字符串str包含在调用中指定的列表中时,此测试成功asList,这方便地采用可变数量的参数。