0

I want the following if statement to compare against multiple strings but when i compare against more than one it gives me the error message that I created. Below is the code which does not work.

The variables are test = 'c3400553' and test2 = 'c3400554'

if (!uname.getText().toString().matches("[cC][0-9]{7}") ||
     !uname.getText().toString().equals(test) ||
     !uname.getText().toString().equals(test2)
    ) {
   uname.setError("Incorrect ID Format");
}

Below is the code which works for one comparison.

String test = "c3400553";
...

if (!uname.getText().toString().matches("[cC][0-9]{7}") ||
         !uname.getText().toString().equals(test)
        ) {
          uname.setError("Incorrect ID Format" );
}

I don't understand what the issue is

3
  • 1
    Check your conditions. Make sure you use && and || where needed. Also check the usage of ! (not operator). Above all, provide a minimal reproducible example Commented Apr 24, 2016 at 12:08
  • uname refers to an edit text field from user input Commented Apr 24, 2016 at 12:09
  • The condition in your "multiple string test" will always return true. It's a bit like (x != 1) || (x != 2) where what you really want is (x != 1) && (x != 2).In your case what you probably want is: (!uname.getText().toString().matches("[cC][0-9]{7}") && (!uname.getText().toString().equals(test) && !uname.getText().toString().equals(test2)) ) Commented Apr 24, 2016 at 12:17

1 Answer 1

1

That's because you either need to remove some !, or you need to replace your || by &&.

It depends on what you are trying to achieve. If you want the id to be declared incorrect if it doesn't match the format AND if it is not equal to test AND ALSO not equal to test2, then the solution is this :

if (!uname.getText().toString().matches("[cC][0-9]{7}") && 
    !uname.getText().toString().equals(test) &&
    !uname.getText().toString().equals(test2) ) {

      uname.setError("Incorrect ID Format" );
}

Otherwise, if what you want to do is to check whether uname matches the format, and is NOT equal to test and test2, then the problem is that you need to remove the ! before comparisons with test and test2 :

if (!uname.getText().toString().matches("[cC][0-9]{7}") || 
    uname.getText().toString().equals(test) ||
    uname.getText().toString().equals(test2) ) {

     uname.setError("Incorrect ID Format" );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.