if else 在 for 循环中循环迭代 json 数组,else 块中有自定义异常
if else loop inside a for loop iterating over a json array with custom exception in else block
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 仅当 none 个元素满足 if 条件时才阻塞。请帮忙
我想你可以这样做:
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,这意味着 none 个元素满足条件,然后它会抛出错误(在循环结束后)。
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 仅当 none 个元素满足 if 条件时才阻塞。请帮忙
我想你可以这样做:
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,这意味着 none 个元素满足条件,然后它会抛出错误(在循环结束后)。