convert arraylist to html table

12,689

Replace

    for (int i = 0; i < ex.getExpenses().size(); i++) {
        out.println("<td>" + ex.getExpenses().get(i) + "</td>");
        if (i>0 && i%4==0) {
            out.println("</tr><tr>");
        }
    }

with

    for (int i = 0; i < ex.getExpenses().size(); i++) {
        if (i>0 && i%4==0) {
            out.println("</tr><tr>");
        }
        out.println("<td>" + ex.getExpenses().get(i) + "</td>");
    }

By the way. Create separate class Expenses that contains 4 fields. It will be much cleaner and easier to convert this to html. You can write special separate method for converting Expenses to html table row.

Share:
12,689

Related videos on Youtube

Gipsy
Author by

Gipsy

Updated on June 04, 2022

Comments

  • Gipsy
    Gipsy almost 2 years

    how do i retrieve my arraylist into html table?

    my arraylist:

    [
    1, 2011-05-10,  1,  22.0, 
    2, 2011-05-10,  2,  5555.0, 
    3, 2011-05-11,  3,  123.0, 
    4, 2011-05-11,  2, 212.0, 
    5, 2011-05-30,  1,  3000.0, 
    6, 2011-05-30,  1,  30.0, 
    7, 2011-06-06,  1,  307.0, 
    8, 2011-06-06,  1,  307.0 ]
    
    out.println("<html>");
            out.println("<head>");
            out.println("<title>Counter</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<table border=\"1\">");
            out.println("<tr>");
            for (int i = 0; i < ex.getExpenses().size(); i++) {
                out.println("<td>" + ex.getExpenses().get(i) + "</td>");
    
                if (i>0 && i%4==0) {
                    out.println("</tr><tr>");
    
                }
    
            }
            out.println("</tr>");
            out.println("</table>");
            out.println("</body>");
            out.println("</html>"); 
    

    this doesn't really work, since arraylist starts with 0, it gives me the table that looks like this: enter image description here

    how do i get the table that looks like this:

    1 2011-05-10  1  22.0
    2 2011-05-10  2  5555.0 
    3 2011-05-11  3  123.0 
    4 2011-05-11  2  212.0 
    5 2011-05-30  1  3000.0
    6 2011-05-30  1  30.0
    7 2011-06-06  1  307.0
    8 2011-06-06  1  307.0
    
    • Manse
      Manse almost 12 years
      use a separate counter variable - initialise it at 1 and then check count%4 = 0
    • Joachim VR
      Joachim VR almost 12 years
      Or adjust the condition to draw a new row: if (i>0 && (i+1)%4==0) {
    • Gipsy
      Gipsy almost 12 years
      could you show me where i initialize it in code and loop through it, because i've tried and all i get is a messy table
    • Gipsy
      Gipsy almost 12 years
      thanks, i've just read your second comment and it works well. thanks again!
  • unbeli
    unbeli almost 12 years
    why would you output a useless empty row at the end? And why not i%4==1?