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();
}
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) { . . .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With