Search code examples
javabooleanstring-comparisonboolean-operations

How to compare text input to multiple strings?


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


Solution

  • 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" );
    }