<body>
    <%
        int apps = 11;
        out.println("<div>");
        out.println("<table>");
        StringBuilder Row1 = new StringBuilder();
        Row1.append("<tr>");
        StringBuilder Row2 = new StringBuilder();
        Row2.append("<tr>");
        StringBuilder Row3 = new StringBuilder();
        Row3.append("<tr>");
        for (int i = 0; i < apps; i++) {
            if (i % 2 == 0) {
                Row1.append("<td>" + i + "</td>");
            }
            if (i % 2 == 1) {
                Row2.append("<td>" + i + "</td>");
            }
        }
        Row1.append("</tr>");
        Row2.append("</tr>");
        out.println(Row1.toString());
        out.println(Row2.toString());
        out.println("</table>");
        out.println("</div>");
    %>
</body>

this is my jsp page,

Currently i'm getting the output as

0 1 2 3 4 5 6 7 8 9 10

Now I need the output as

In row 1:

0 3 6 9 12 15

In row 2:

1 4 7 10 13

In row 3:

2 5 8 11 14

If I have 100 numbers, output needs as above.

有帮助吗?

解决方案

I am a PHP developer, I did it in php way. But logic is same..

<?php

$apps = 100;
for ($i = 0; $i < $apps; $i++) {
    if ($i % 3 == 0) {
        $row1 .= "<td>" .$i ."</td>";
    }
    if ($i % 3 == 1) {
        $row2 .= "<td>" .$i ."</td>";
    }
    if ($i % 3 == 2) {
        $row3 .= "<td>" .$i ."</td>";
    }
}
?>
<table>
<tr><?php echo $row1; ?></tr>
<tr><?php echo $row2;?></tr>
<tr><?php echo $row3; ?></tr>
</table>

Change appropriate places and check..

其他提示

for (int i = 0; i < apps; i++) {
    if (i % 3 == 0) {
        Row1.append("<td>" + i + "</td>");
    } else if (i % 3 == 1) {
        Row2.append("<td>" + i + "</td>");
    } else if (i % 3 == 2) {
        Row3.append("<td>" + i + "</td>");
    }
}

ADDITION:

you haven't printed out the third row.. try to add this:

Row3.append("</tr>");
out.println(Row3.toString());

I would encourage you to stop using java code in your jsp pages as that can become quite brittle. An alternative would be to use JSTL. Your page would then be translated to something like this:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<body>
<table>
    <c:set var="apps" value="10"/>
    <tr>
    <c:forEach var="i" begin="0" end="${apps}" step="3">
       <td><c:out value="${i}"/></td>
    </c:forEach>
    </tr>
    <tr>
    <c:forEach var="i" begin="1" end="${apps}" step="3">
       <td><c:out value="${i}"/></td>
    </c:forEach>
    </tr>
    <tr>
    <c:forEach var="i" begin="2" end="${apps}" step="3">
       <td><c:out value="${i}"/></td>
    </c:forEach>
    </tr>
</body>
</html>

This way it is easier to keep a clean separation between your buisness-logic and your view-logic (which generates the page).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top