简体   繁体   中英

issue with variable for loop java

I am complete beginner. I have a for that prints with a syso the value of a jsonText. How can I do to save this value in a variable concatening all the values of the length of the for. here is my code. Thank you.

for(int i=0;i<nodes.getLength();i++) {
    Element element = (Element)nodes.item(i);

    Map<String, String> obj=new LinkedHashMap<String, String>();
    obj.put("category",getElementValue(element,"category"));
    obj.put("title",getElementValue(element,"title"));
    obj.put("date",getElementValue(element,"pubDate"));
    obj.put("description",getElementValue(element,"description"));
    obj.put("content",getElementValue(element,"content:encoded"));
    StringWriter out = new StringWriter();
    JSONValue.writeJSONString(obj, out);
    String jsonText = out.toString();
    System.out.println(jsonText);

}

You can use a StringBuilder to concatenate the jsonText.

   StringBuilder builder = new StringBuilder();
   for(int i=0;i<nodes.getLength();i++) {
      Element element = (Element)nodes.item(i);

      Map<String, String> obj=new LinkedHashMap<String, String>();
      obj.put("category",getElementValue(element,"category"));
      obj.put("title",getElementValue(element,"title"));
      obj.put("date",getElementValue(element,"pubDate"));
      obj.put("description",getElementValue(element,"description"));
      obj.put("content",getElementValue(element,"content:encoded"));
      StringWriter out = new StringWriter();
      JSONValue.writeJSONString(obj, out);
      String jsonText = out.toString();
      System.out.println(jsonText);
      builder.append(jsonText);
   }

Simple,

StringBuilder builder = new StringBuilder();
for(int i=0;i<nodes.getLength();i++) {
    ..... your existing code ....
    builder.append(jsonText);
}

String finalData = builder.toString();

You could create a global variable outside the for-loop:

String allStrings = "";

then use the string1.concat(string2); method:

allStrings = allStrings.concat(jsonText);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM