-1

下面的 ismy 代码在最后一个循环中工作正常唯一的问题我想改变一点我怎么知道是最后一个循环?我的代码在 forloop 结束时不满足这个条件 if(i == school5.length()-1) 而不是用 . 我会做什么请帮帮我

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; 
        }
    }
}
4

3 回答 3

2

if (i == school5.length()-1)永远是假的,因为它在里面if (i == 0)

于 2013-10-11T12:55:50.167 回答
1

if(i == school5.length()-1)

永远不会为真,因为在此条件之前,只会在i==0.

唯一的情况是

if(i == school5.length()-1)

当 i == 0 & json 数组长度为 1 时为真

于 2013-10-11T12:57:00.553 回答
1

此外,最好不要保留“school5.length();”。在 for 循环中以获得更好的性能。

处理这样的事情应该更好

int size = school5.length();
for (int i = 0; i < size; i++) {
   // your loop
}
于 2013-10-11T13:00:37.227 回答