【问题标题】:if else loop inside a for loop iterating over a json array with custom exception in else blockif else 循环在 for 循环中迭代一个 json 数组,在 else 块中有自定义异常
【发布时间】:2017-04-13 13:32:00
【问题描述】:
for(int i =0; i< jarray.length;i ++){
JsonObject jobj = jarray.getJsonObject(i);
//i am running a database query here to fetch a record based on a value in  the json object
//i have my if block here
if(the codition is true){

}else{
throw new CustomException
}

}

我的问题是,对于第一次迭代,如果 IF 条件失败,它不会迭代数组中的剩余元素并直接转到 else 块,我如何让它遍历整个数组并转到 else 块仅当没有任何元素满足 if 条件时。请帮忙

【问题讨论】:

    标签: arrays json core


    【解决方案1】:

    我认为你可以这样做:

    var conditionSatisfied = false;
    
    for(int i =0; i< jarray.length;i ++){
        JsonObject jobj = jarray.getJsonObject(i);
    
        if(the condition is true){
           conditionSatisfied = true;
        }
    }
    
    if(!conditionSatisfied) {
        // throw error
    }
    

    循环遍历整个数组,如果有任何元素的条件为真,那么布尔变量conditionSatisfied 将为true。否则conditionSatisfied 保持false,表示没有一个元素满足条件,然后会抛出错误(循环结束后)。

    【讨论】:

      猜你喜欢
      • 2015-11-13
      • 2017-08-02
      • 2019-12-04
      • 2012-11-13
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      相关资源
      最近更新 更多