if statement - Trouble with formatting input as JSON format with java -


hi have trouble java program. i'm writing program asks user book's title, author, price, , isbn. takes input stores book class stores input , has tostring method prints out contents similar json formatting. books class uses array list store book objects , has tostring method prints out entire set of books in json format. problem doesn't format properly. problem lies within if , else statement in code. heres code:


import java.util.arraylist; public class books {   private arraylist<book> books;    public books()   {     books = new arraylist<book>();   }   public void add(book bk)   {     books.add(bk);   }   public string tostring()   {     string temp = "{\n ";     temp = temp + "  \"books:\": [\n";     int bookcount = 0;     (book bk : books) {       temp += bk.tostring();       bookcount++;//add +1 bookcount       if (bookcount < books.size()-1) {         temp += ",\n";       }       else {         temp += "\n  ]\n}\n";       }     }     return temp;   } } 

when run program looks this:

results

my goal have this:

wantedresults

so after parsing first book correctly adding ",\n"; . each book being parsed after adds "\n ]\n}\n"; want added last one. :( please help.

thanks in advance

the problem increase bookcount value before checking condition.

if not using enhanced loop, code this

for (int bookcount = 0; bookcount < books.size()-1; bookcount++)  {     book book = books.get(i);     //  print book     //  check condition } 

bookcount should added after checking condition


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -