1

Java: stores and serializes objects from a matrix

 3 years ago
source link: https://www.codesd.com/item/java-stores-and-serializes-objects-from-a-matrix.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java: stores and serializes objects from a matrix

advertisements

I know this could be a very easy question but I cant get my code to work properly. I need to write into a XML file in an field an example like this: 1-A,2-C,3-D,...25-A For this I have the total number of items (1..25) and the answers given for these items that I retrieve from another class. Here is what I use to write this kind XML and what does not work as I should work.

for (int i=0;i<=30;i++){
                nRespuesta  = i+1;
                nRespuestaString = Integer.toString(nRespuesta);
                Respuesta = Verbal.getRespuestas(i);
                RespuestaString = nRespuestaString+"-"+Respuesta+",";

            }
serializer.startTag(null, "RESPUESTAS");
            serializer.text("RespuestaString");
            serializer.endTag(null, "RESPUESTAS");

With this code it only shows the last item, how could I show all? Thank you


UPDATE Answer now uses StringBuilder for better performance.

You need to concatenate the string rather than overwrite on each loop iteration so modify your code to the following:

StringBuilder sb = new StringBuilder();
for (int i=0;i<=30;i++){
                nRespuesta  = i+1;
                nRespuestaString = Integer.toString(nRespuesta);
                Respuesta = Verbal.getRespuestas(i);
                //Note the change on the line below
                sb.append(nRespuestaString).append("-").append(Respuesta).append(",");
            }
serializer.startTag(null, "RESPUESTAS");
            serializer.text(sb.toString());
            serializer.endTag(null, "RESPUESTAS");


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK