Carl
Carl

Reputation: 23

Creating an HTML table in Java

I have a problem in my code when I am creating a table in Java using HTML. This is my code:

for(int station : stations){
   String rowcolor = null;
   String stationnum = Integer.toString(station);
   String lastDate = pollData(station); //CALL GET LAST 
   String status = determineStatus(station, lastDate); // CALL DETERMINE STATUS

    switch(status){
       case " ONLINE":
           rowcolor = (" <tr bgcolor=\"#5FFF33\">");
           break;
       case " OFFLINE":
           rowcolor = (" <tr bgcolor=\"red\">");
           break;
       case " DELAYED":
           rowcolor = (" <tr bgcolor=\"yellow\">");
           break;
   }

    out.write("<html>" +
       "<body>" +
       "<table border ='1'>" +
       "<tr>" +
       "<td>Station Number</td>" +
       "<td>Station Name</td>" +
       "<td>Status</td>" +
       "<td>As of Date</td>" +
       "</tr>");

    out.write(rowcolor + "<td>");
    out.write(stationnum);
    out.write("</td><td>");
    out.write(stationnname[id]);
    out.write("</td><td>");
    out.write(status);
    out.write("</td><td>");
    out.write(lastDate);
    out.write("</table>" +
       "</body>" +
       "</html>"); 
     id++; 
    out.close(); 
   }   

   }catch (IOException e) {
   System.err.println(e);
   } 

and this is the output:

enter image description here

When I remove the out.close(); part, the output is this:

enter image description here

As you can see, the image there is a problem in creating the table. Something is not right but I can’t find a way to fix it. Please help me; thanks in advance.

Upvotes: 0

Views: 20266

Answers (2)

Phil
Phil

Reputation: 164760

Look at what you're writing to the output buffer and where.

Inside your for loop, you are writing a complete HTML document (ie <html><body>...</body></html>) and an entire table with header row and one data row.

What I assume you want to do is keep writing table rows to the one table. To do so, write the aforementioned tags outside your for loop

out.write("<html><body><table border=\"1\"><thead>" +
        "<tr><td>Station Number</td><td>Station Name</td>" +
        "<td>Status</td><td>As of Date</td></tr></thead><tbody>");
for(int station : stations) {
    // get data, determine rowcolor, etc
    out.write(rowcolor + ... + "</tr>");
}

out.write("</tbody></table></body></html>");
out.close();

Upvotes: 4

flyingfox
flyingfox

Reputation: 13506

As Phil said,out.close(); is inside the for loop,you need to change it to outside the for loop,due to if it's inside loop,out will close for the first iterate,and will not work for other records

for(int station : stations){

}
out.close();

Upvotes: 1

Related Questions