oliver_13 oliver_13 - 7 months ago 8
Java Question

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'

else 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";
...

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


I dont understand what the issue is

Answer

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 :

else 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 :

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