Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment counter with loop

Tags:

java

jsp

jstl

This question is related to my previous question :

Jsp iterate trough object list

I want to insert counter that starts from 0 in my for loop, I've tried several combinations so far :

1.

<c:forEach var="tableEntity" items='${requestScope.tables}'>    <c:forEach var="rowEntity" items='${tableEntity.rows}' varStatus="count">                     <c:out value="${count}" />     </c:forEach> </c:forEach> 

2.

<c:set var="count" value="0" scope="page" /> <c:forEach var="tableEntity" items='${requestScope.tables}'>    <c:forEach var="rowEntity" items='${tableEntity.rows}'>          <%=count++%>   <c:out value="${count}" />     </c:forEach> </c:forEach> 

Problem with first approach is that outer loop has 3 items and inner loop has 7 items, so for each outer item the count starts from 0. The second one I get compile error. Here is basically what I want :

counter = 0; outer for loop      inner for loop         counter++;        //cout/echo/print counter value should start from 0     end inner loop end outer loop 

I'm just not totally familiar with the syntax. thank you

like image 923
London Avatar asked Feb 01 '11 12:02

London


People also ask

How do you counter an increment loop in python?

Increment variable in loop python In python, to increment a variable value in a loop, we can use the while loop directly for increasing or decreasing the iteration value. After writing the above code (increment variable in loop python), Ones you will print “my_list[i]” then the output will appear as an “ 11 13 15 ”.

How do you increment the value of a for loop?

A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.

How would you increment a counter variable?

The most simple way to increment/decrement a variable is by using the + and - operators. This method allows you increment/decrement the variable by any value you want.

How do you give a loop in two increment?

A common idiom is to use the comma operator which evaluates both operands, and returns the second operand. Thus: for(int i = 0; i != 5; ++i,++j) do_something(i,j);


1 Answers

Try the following:

<c:set var="count" value="0" scope="page" />  //in your loops <c:set var="count" value="${count + 1}" scope="page"/> 
like image 129
dogbane Avatar answered Sep 22 '22 11:09

dogbane