How can I test a string against multiple others in Java?

comparison, java, string

Solution

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

Problem

``` The operator || is undefined for the argument type(s) boolean, String ``` I keep getting the above error message with the following `if` statement: ``` 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(); } ```

Original source

Related problems