java 运算符 || 参数类型未定义 boolean, String

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

The operator || is undefined for the argument type(s) boolean, String

javaandroid

提问by Ciaran

I keep getting the above error message with the following IF statement. Any help is appreciated.

我不断收到带有以下 IF 语句的上述错误消息。任何帮助表示赞赏。

public void sendMessage(View button) {
        String mName = Name.getText().toString();
        String mGuess = Guess.getText().toString();
        if (mGuess != "1" || "2" || "3" || "4" || "5" || "6" || "7" || "8" || "9" || "10") {
            Toast.makeText(MainActivity.this,
                    "The number you entered was invalid. Please try again.", Toast.LENGTH_LONG).show();
        }

回答by Ted Hopp

First, you should generally not be using !=to compare strings; use equals()instead. The ==and !=operators will only test if the strings are identical objects; they do not test for equal values. Second, you need to expand the expression like this:

首先,您通常不应该!=用于比较字符串;使用equals()来代替。的==!=如果字符串相同的物体运营商将只测试; 它们不测试相等的值。其次,您需要像这样扩展表达式:

if (!mGuess.equals("1") || !mGuess.equals("2") || /* etc */) { . . .

Finally, this logic doesn't actually make any sense. The condition will always be true (mGuesswill always be "not equal" to at least all but one of the test strings). You probably want:

最后,这个逻辑实际上没有任何意义。条件将始终为真(mGuess将始终“不等于”至少除一个测试字符串之外的所有字符串)。你可能想要:

if (!mGuess.equals("1") && !mGuess.equals("2") && /* etc */) { . . .

A more succinct way of doing this would be:

更简洁的方法是:

List<String> validStrings = Arrays.asList("1", "2", ...);
if (!validStrings.contains(mGuess)) { ...

(You could declare validStringsas a staticclass member to save creating one each time through the method. Also, see the answer by assyliasfor how to use a HashSetinstead of an ArrayListfor the lookup; it will do the lookup faster.)

(您可以声明validStringsstatic类成员以保存每次通过该方法创建一个。另外,请参阅assylias 的答案以了解如何使用 aHashSet而不是 anArrayList进行查找;它会更快地进行查找。)

P.S. As mentioned by assylias and also by kcoppock in a comment, you should consider parsing the input as an intvalue and then doing a numeric test. The difference would be that parsing as an intwould treat, say, "07" the same as "7". If you want to allow that, then this code will do the job:

PS 正如 assylias 和 kcoppock 在评论中所提到的,您应该考虑将输入解析为一个int值,然后进行数字测试。不同之处在于解析为 anint会将“07”视为与“7”相同。如果您想允许这样做,那么此代码将完成这项工作:

boolean ok = false;
try {
    int guess = Integer.parseInt(mGuess);
    ok = guess >= 1 && guess <= 10;
} catch (NumberFormatException ignored) {
}
if (!ok) { . . .

回答by assylias

You need to make each condition explicit as already explained. A more compact way to write it would be:

正如已经解释的那样,您需要明确每个条件。一种更紧凑的编写方式是:

Set<String> oneToTen = new HashSet<String> (Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");

if (!oneToTen.contains(mGuess)) {

Alternatively, if you know that mGuess is a number, you could parse it to an integer first:

或者,如果您知道 mGuess 是一个数字,则可以先将其解析为整数:

int guess = Integer.parseInt(mGuess);
if (guess < 0 || guess > 10) {
}

回答by assylias

The causeof the compiler error1is that the expression

编译错误1原因是表达式

mGuess != "1" || "2" || ..

is parsed equivalently to

被等效地解析为

((mGuess != "1") || "2") || ..

However, the type of myGuess != "1"is boolean, so the above expression is typed as

但是, 的类型myGuess != "1"boolean,所以上面的表达式被键入为

((boolean) || String) || String) || ..

but boolean || Stringis invalid, as per the compiler error:

boolean || String无效,根据编译器错误:

The operator || is undefined for the argument type(s) boolean, String

运算符 || 参数类型未定义 boolean, String



1See one of the other answers for solutions.

1有关解决方案,请参阅其他答案之一。

回答by Reimeus

You need to use &&to evaluate your negative expressions, use .equalsfor Stringcomparisons, and have syntactically correct expressions in your ifstatement:

您需要使用&&来评估否定表达式,.equals用于String比较,并在if语句中使用语法正确的表达式:

if (!mGuess.equals("1") && !mGuess.equals("2") && ...

Also see: Java String.equals versus ==

另请参阅:Java String.equals 与 ==