2012-05-15 147 views
1

如何將我的arraylist檢索到html表中?將arraylist轉換爲html表

我的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>"); 

這並沒有真正的工作,因爲ArrayList中以0開始,它讓我看起來像這樣的表:enter image description here

請問如何看起來表像這樣:

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 
+1

使用一個單獨的計數器變量 - 初始化它在1然後檢查'計數%4 = 0' – ManseUK

+2

或調整條件以繪製一個新行:if(i> 0 &&(i + 1)%4 == 0 ){ –

+0

你能告訴我我在哪裏初始化它在代碼中,並通過它循環,因爲我試過了,我得到的是一張凌亂的表 – Gipsy

回答

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

順便說。創建包含4個字段的獨立類Expenses。將它轉換爲html會更簡單和容易。您可以編寫特殊的單獨方法將Expenses轉換爲html表格行。

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>"); 
+0

+1表示條件,但是i> 0現在無用 – Kousalik

+0

爲什麼你會在最後輸出無用的空行?爲什麼不是%4 == 1? – unbeli

-1

第一件事: 獲取arrylist成獨立的變量,然後用foreach itarate它,而不是調用get()和get(我)多次,然後換你的,如果條件

if ((i+1)%4==0) { 
      out.println("</tr><tr>"); 
    } 
秒件事: 使用 StringBuilder類來連接輸出字符串,則只有一個 out.print打印