1

如何将我的数组列表检索到 html 表中?

我的数组列表:

[
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>"); 

这实际上不起作用,因为 arraylist 以 0 开头,它给了我如下所示的表:在此处输入图像描述

我如何获得如下所示的表格:

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
4

3 回答 3

3

代替

    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>");
        }
    }

    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>");
    }

顺便一提。创建Expenses包含 4 个字段的单独类。将其转换为 html 会更干净、更容易。您可以编写特殊的单独方法来转换Expenses为 html 表格行。

于 2012-05-15T08:45:57.737 回答
0

更改i(i+1)

[
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+1)%4==0) {
                out.println("</tr><tr>");

            }

        }
        out.println("</tr>");
        out.println("</table>");
        out.println("</body>");
        out.println("</html>"); 
于 2012-05-15T08:46:09.733 回答
-1

第一件事:将 arrylist 放入单独的变量中,然后使用 foreach 对其进行迭代,而不是重复调用 get() 和 get(i),然后更改您的 if 条件

if ((i+1)%4==0) {
          out.println("</tr><tr>");
     }

第二件事:使用StringBuilder类连接输出字符串,然后只用一个打印它out.print

于 2012-05-15T08:47:18.870 回答