【问题标题】:Check multiple null values in if statement using OR and store errors in an array使用 OR 检查 if 语句中的多个空值并将错误存储在数组中
【发布时间】:2019-11-21 08:02:06
【问题描述】:

当用户提交表单时,我想检查表单中的多个文本字段并检查它是否为空,它必须显示哪个输入字段为空白

String A = request.getparameter("a");
String B = request.getparameter("b");
String C = request.getparameter("c");
if(A==null || B==null || C==null)
{

//Here I want to store the corresponding errors in an arrayfield and it should display which field is empty.

}

【问题讨论】:

    标签: java


    【解决方案1】:

    把实现改成这个

    if(A==null){
    //A is null, add message
    }
    else if(B==null){
    //error message against B
    }
    else if(C==null){
    //error message against C
    }
    

    使用 Apache Commons StringUtils.isEmpty(str),它会检查空字符串并优雅地处理 null。

    所以它会像

    if(StringUtils.isEmpty(A)){ 
    
    }
    

    【讨论】:

    • StringUtils.isEmpty(A) 不工作。错误显示方法 isEmpty(String) 未定义类型 StringUtils
    • 你导入Apache Commons了吗?
    • 没有。那怎么导入?我正在使用 Maven。我需要输入哪个导入语句。
    【解决方案2】:

    //在onCreate方法里面做这个

       //make this variable globle
    
       ArrayList<MyVariableNameValue> nullStringList=new ArrayList<>();
        for (MyVariableNameValue nullString: checkNull()) {
            Log.d("nullsize", "onCreate: "+nullString.getName());
        }
        //up to here
    

    //创建getter方法类,将变量名和值存储在mainactivity中或mainactivity之外

     public class MyVariableNameValue{
        String name,value;
        public MyVariableNameValue(String name,String value){
            this.name=name;
            this.value=value;
        }
    
        public String getName() {
            return name;
        }
    
        public String getValue() {
            return value;
        }
    }
    

    //在maiactivity中创建一个返回null变量值和名称的方法

     public ArrayList<MyVariableNameValue> checkNull(){
        nullStringList.clear();
      String A = request.getparameter("a");
      String B = request.getparameter("b");
      String C = request.getparameter("c");
        ArrayList<MyVariableNameValue> checkString = new ArrayList<>();
        checkString.add(new MyVariableNameValue("A",A));
        checkString.add(new MyVariableNameValue("B",B));
        checkString.add(new MyVariableNameValue("C",C));
        for (MyVariableNameValue myString: checkString) {
            if(TextUtils.isEmpty(myString.getValue())){
                nullStringList.add((myString));
            }
    
        }
        return nullStringList;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多