我有一个循环遍历数组的 for 循环。
for(int i = 0; i<=(clientListpost.length -1); i++){
if(clientpost[i] == true) {
if((clientpost[i+1] == true) || (clientpost[i+2] == true) || (clientpost[i+3] == true)) {
clientString[i] = client[i] + ",";
} else {
clientString[i] = client[i];
}
}
}
如果以下数组之一包含 true,我会检查第二个 if else。
如果我有大约 40 个以下数组,如何压缩第二个 if 条件?
我不能使用indexOf(),因为它总是在所有索引中搜索。
示例:
My clientListpost => [false, false, false, false] 取决于表单上选择的内容(如果选择=> true)
我的 clientpost 现在生成 8 个数组,以使第二个 if 条件起作用 => if((clientpost[i+1] == true) || (clientpost[i+2] == true)..
我这样做是因为如果我点击最后一个数组之一,它会给我一个错误:数组 (5,6,7..) 不存在。
我的 clientString => ["","","",""] 为空。因为如果 clientpost 数组为 false,它就会有一个 String 值。
我的客户 => [1015, 1035, 1040, 1070] 将值赋予 clintString 数组
最后我只是将它们串成一排:
String clientUrl = "";
for(int i = 0; i<=(clientListpost.length -1); i++){
clientUrl += clientString[i].toString();
}
输出:
如果仅选择 1015 => 1015
如果选择 1030 和 1045 => 1030,1045
如果选择 1045 和 1070 => 1045,1070
提前致谢!
最佳答案
我将在这里做出一些假设(另请参阅我在对您的问题的评论中提出的问题):
- 你确实需要像这样构建数组
- 您已确保没有抛出 ArrayIndexOutOfBoundsException
不检查是否添加了任何后续元素,而是向后迭代:
boolean subsequentElementsSelected = false;
for(int i = clientListpost.length -1; i >= 0; i--){
if(clientpost[i]) { //or clientpost[i] == true
if(subsequentElementsSelected ) {
clientString[i] = client[i] + ",";
} else {
//only true for the last element to be added/set
clientString[i] = client[i];
}
//once we've added an element at the end this will stay true
subsequentElementsSelected = true;
}
}
来自您的评论:
I do reduce them into a single string at the end.
如果不需要 clientString
数组,只需附加到字符串并根据需要添加逗号:
StringBuilder builder = new StringBuilder();
for(int i = 0; i <= clientListpost.length -1; i++){
if(clientpost[i]) { //or clientpost[i] == true
//if there's already something in the String, add a comma first
if(builder.length() > 0) {
builder.append(",");
}
//add the element
builder.append(client[i]);
}
}
clientUrl += builder.toString(); //assumes there's more in clientUrl, otherwise just assign
关于java - Ramining 数组 - 如果包含 "true",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60432169/