在for循环中迭代值数组时,循环在null之后中断,我尝试了if with condition但它在null处中断
String[] arr = {
a="10A";
b="12B";
c="";
d="13C";
};
StringBuilder ret = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
String key = arr[i];
i++;
String val = arr[i];
ret.append(String.format("%s%02x%s", key, val.length() / 2, val));
//if (a==null || b==null || c==null || d==null){
//continue;
//}
}
}
}
return ret.toString();
}
帮助了解要使用的内容,以使循环不会中断,并跳过空值并返回其余值
答案 0 :(得分:0)
您的代码有一些问题。
continue
之前的条件仅测试在循环外部定义的变量,因此,如果它在一次迭代中失败,则它在所有迭代中都失败;您可能想改为测试key
和/或val
我认为您正在寻找这样的东西:
String[] arr = {
"a","10A",
"b","12B",
"c","",
"d","13C"
};
StringBuilder ret = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
String key = arr[i++];
String val = arr[i];
if (key == null || val == null || key.isEmpty() || val.isEmpty()) {
continue;
}
ret.append(String.format("%s%02x%s", key, val.length() / 2, val));
}
return ret.toString(); // a0110Ab0112Bd0113C