java: generador de cadenas

Quiero anexar , to a StringBuilder if the variable a is less than the length of the Array.
I am incrementing the variable a everytime, and I am using the following code:

for(int n=0;n<fieldMap.length();n++)
{
    int a=0;
    JSONObject object = fieldMap.getJSONObject(n);              
    String type= object.getString("type");
    String name= object.getString("name");

    createTable.append(name +" ");
    createTable.append(type);
    a++;

    if(!(a==(fieldMap.length()-1))) {
        createTable.append(",");
    }                       
}

But it is appending , at the end also which I don't want. How can I solve this problem?

Muchas Gracias

preguntado el 08 de noviembre de 11 a las 12:11

Also its better to append without checking and strip the comma after the loop, you can improve performance -

1 Respuestas

Inicializar a outside the for loop:

int a=0;
for(int n=0;n<fieldMap.length();n++){

O simplemente usa n en lugar de a.

You can also simplify your logic slightly by writing the comma first:

 for(int n=0; n < fieldMap.length(); n++){
     JSONObject object = fieldMap.getJSONObject(n);             
     String type = object.getString("type");
     String name = object.getString("name");

     if (n != 0) {
         createTable.append(",");
     }
     createTable.append(name + " ");
     createTable.append(type);
}  

respondido 08 nov., 11:16

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.