Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

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

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();
        }
like image 326
Ciaran Avatar asked Nov 28 '22 17:11

Ciaran


1 Answers

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:

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

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

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 validStrings as a static class member to save creating one each time through the method. Also, see the answer by assylias for how to use a HashSet instead of an ArrayList for the lookup; it will do the lookup faster.)

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

boolean ok = false;
try {
    int guess = Integer.parseInt(mGuess);
    ok = guess >= 1 && guess <= 10;
} catch (NumberFormatException ignored) {
}
if (!ok) { . . .
like image 85
Ted Hopp Avatar answered Dec 15 '22 17:12

Ted Hopp