tags:

views:

49

answers:

2

Hello All,

I am having some difficulties in java while comparing between a variable and the next resultset. In my case, I want : if the temp variable = rs.next() then temp ="" else the rs.next() value should be displayed.

This is because I am getting the Tname field many times, so I would like to retrieve it once.

Here is my code

while(rs.next()){

%>
        <tr>
            <td width="238">
                <%temp=rs.getString("TNAME");%> 
                <%=temp%> </td>
            <td><%=rs.getString("ID")%></td>
                    <%
                           if (rs.next().equals(temp){ 
            temp="";
            }


}

rs.close();

%> 
A: 

I think you have two problems:

  1. you're iterating through your loop using rs.next() but inadvertently jumping again by your second rs.next() call.
  2. you're comparing your temp string to rs.next() and not the particular field you're interested in.
Brian Agnew
so, how to do that
maas
It's not very clear (I think) what you want. The above is just based on some apparently obvious problems with your current solution.
Brian Agnew
how to compare the temp which has the tname with rs.next() for the next tname
maas
It may be simpler to pull out all the TNAMEs into a list and then iterate through those in a separate state, rather than mix your comparisons with calls to rs.next(). You'll be separating two areas of complexity (which is most usually a good thin g)
Brian Agnew
A: 

ResultSet#next() returns a boolean, not a String containing the column value you're after. But still then, you really don't want to move the cursor to the next row there. When you go back to the beginning of the while loop, you have effectively skipped one row.

You need to change the logic: compare the currently iterated name with the previously iterated one and only display it when it is different. Then store the currently iterated name as variable so that it can be compared in the next iteration. Here's a kickoff example based on JSTL/EL and a fictive List<Item> which is stored as ${items} in the scope:

<table>
    <c:forEach items="${items}" var="item">
        <tr>
            <td><c:if test="${item.name != previousName}">${item.name}</c:if></td>
        </tr>
        <c:set var="previousName" value="${item.name}" />
    </c:forEach>
</table>

You only need to translate it into old fashioned scriptlets yourself if you insist in using it. The above logic should be self-explaining enough.

BalusC