下面ismy代码是工作正常的问题在最后一个循环我想改变小事我怎么知道是最后一个循环?我的代码不满足这个条件if(i == school5.length() - 1)在forloop结尾而不是替换,用。我会怎样帮助我
JSONArray school5 = json2.getJSONArray("dish_ingredient");
String concatProduct = "";
for (int i = 0; i < school5.length(); i++) {
String name = school5.getJSONObject(i).getString("name");
String subIngredient = school5.getJSONObject(i).getString("sub_ingredients");
if(i == 0){
if (subIngredient.equals(""))
{
if(i == school5.length()-1)
{
concatProduct = " " + "<b>" + name + "</b>"+". " + subIngredient;
}
else
{
concatProduct = " " + "<b>" + name + "</b>"+", " + subIngredient;
}
}
else
{
concatProduct = " " + "<b>" + name + "</b>"+": " + subIngredient;
}
} else {
if (subIngredient.equals(""))
{
concatProduct += " " + "<b>" + name + "</b>"+", " + subIngredient;
}
else
{
concatProduct += " " + "<b>" + name + "</b>"+": " + subIngredient;
}
}
}
答案 0 :(得分:2)
if (i == school5.length()-1)
将始终为false,因为它位于if (i == 0)
答案 1 :(得分:1)
此
if(i == school5.length()-1)
永远不会成立,因为在i==0
之前只会检查此条件。
唯一的情况
if(i == school5.length()-1)
当i == 0&amp;时,为真 json数组长度为1
答案 2 :(得分:1)
此外,不保留“school5.length();”是一个好习惯。在for循环中获得更好的性能。
应该更好地处理类似的事情
int size = school5.length();
for (int i = 0; i < size; i++) {
// your loop
}