如何将文本输入与多个字符串进行比较?

How to compare text input to multiple strings?

我希望以下 if 语句与多个字符串进行比较,但是当我与多个字符串进行比较时,它会给出我创建的错误消息。下面是不起作用的代码。

变量是test = 'c3400553'和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");
}

下面是用于比较的代码。

String test = "c3400553";
...

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

我不明白这是什么问题

那是因为您要么需要删除一些 !,要么需要将 || 替换为 &&

这取决于您要实现的目标。如果您希望 id 在不匹配格式且不等于 test 且也不等于 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" );
}

否则,如果你想做的是检查uname是否匹配格式,并且不等于test和test2,那么问题是你需要在与test比较之前删除!和测试 2:

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

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