tags:

views:

164

answers:

3

Hello all,

I was working on a Java web application, and had the following requirement with respect to looping in my HTML table.

I've a nested for loop inside a while loop(both execute the same # of times, for ex. say 3).

My code looks something like this:

<table>
<thead>...</thead>
<tbody>

    if (patcases != null && patcases.size() > 0) {
                Iterator itr1 = patcases.iterator();
                while (itr1.hasNext()) {
                    ..some code here..

                    System.out.println("DA Email from webpage..."+da.getEmail());
                       int rCount = 0;  
       <tr>                
                       for(int i=0;i<passedValues.length; i++){

                         ...some code here..
       </tr>

                       System.out.println("Printed row..." +rCount);
                rCount ++;
} /*closing of for loop */
}/*closing of while loop */
}/* closing of if loop */
</tbody>
</table>

Now, with this type of looping structure, I get the following on my console:

DA Email from [email protected]
Printed row...0
Printed row...1
Printed row...2
DA Email from [email protected]
Printed row...0
Printed row...1
Printed row...2
DA Email from [email protected]
Printed row...0
Printed row...1
Printed row...2

But the type of output I wanted was, something as follows:
DA Email from [email protected]
Printed row...0
DA Email from [email protected]
Printed row...1
DA Email from [email protected]
Printed row...2

How would I go about doing this?
Any help would be greatly appreciated.

+9  A: 

It looks like you want parallel iteration.

Simply do something like this:

Iterator<?> iter1 = ...;
Iterator<?> iter2 = ...;             // or: int index = 0;

while (iter1.hasNext() &&
           iter2.hasNext()) {        // or: index < MAX

   Object item1 = iter1.next();
   Object item2 = iter2.next();      // or: index++;

   doSomething(item1, item2);        // or: doSomething(item1, index);

}

// perhaps additional handling if one ran out before the other

Note that if at all possible, so you should use parameterized types instead of raw types (Effective Java 2nd Edition, Item 23: Don't use raw types in new code).

polygenelubricants
This is almost always a code smell pointing towards creating a class that holds both pieces of related information and storing objects of that class in a single collection.
Mark Peters
@Mark: Good insight, but parallel iteration is mentioned (as limitation of for-each) both in language guide (http://download-llnw.oracle.com/javase/1.5.0/docs/guide/language/foreach.html) and _Effective Java 2nd Edition, Item 46: Prefer for-each loops to traditional for loops_.
polygenelubricants
Sure, but that doesn't promote it as a concept. I'm not trying to say you're wrong or that there aren't valid uses for parallel iteration. One perfectly valid use would be to check the order-sensitive equality of two collections. But in general, if I saw it in code I was reviewing it'd be a big red flag since more often than not parallel data structures are used in ignorance of creating a type.
Mark Peters
+2  A: 

It seems to me that you don't want a nested for loop at all. You just want a counter which gets incremented in the while loop:

if (patcases != null && patcases.size() > 0) {
     Iterator itr1 = patcases.iterator();
     int index = 0;
     while (itr1.hasNext()) {
         ..some code here..
         System.out.println("DA Email from webpage..."+da.getEmail());
         if (index < passedValues.length) {
             System.out.println("Printed row..." + index);
         } else {
             // Hmm, didn't expect this...
             // (Throw exception or whatever)
         }
         index++;
     }
     if (index != passedValues.length) {
         // Hmm, didn't expect this...
         // (Throw exception or whatever)
     }
 }
Jon Skeet
You should change `rCount` to `index` in `Printed row...` statement.
Alexander Pogrebnyak
@Alexander: Thanks, fixed.
Jon Skeet
@Jon : you have i++ in the if() statement, I'm assuming it's to say i++ at the end of the if loop, but with this code, I get the foll: o/p DA Email from [email protected] row...0DA Email from [email protected] row...0DA Email from [email protected] row...0
Pritish
@Pritish: Doh - that "i++" shouldn't be there at all. It shouldn't be printing "row 0" multiple times though.
Jon Skeet
@Jon: Sorry, I'd int index = 0 declared inside the while loop() that was causing the problem. Have sorted that out.Thanks for your help!
Pritish
A: 

"Nested for loops" doesn't mean "interlaced for loops". For example, saying:

for (i = 0; i < 3; i++) {
    print("i: " + i);

    for (j = 0; j < 3; j++)
        print("\tj: " + j);
}

prints the following:

i: 0
    j: 0
    j: 1
    j: 2
i: 1
    j: 0
    j: 1
    j: 2
i: 2
    j: 0
    j: 1
    j: 2

What you seem to want is:

i: 0
    j: 0
i: 1
    j: 1
i: 2
    j: 2

Instead of nesting for loops, you would just use a separate counter in the same loop:

j = 0;

for (i = 0; i < 3; i++) {
    print("i: " + i);

    print("\tj: " + j);
    j++;
}
Joey Adams
Why bother with the `j` counter in the final example, when by definition you want it to be identical to `i` at all times?
Andrzej Doyle
It is possible to put `j` in the `for` statement, like this: `for (i = 0, j = 0; i < 3; i++, j++) {`
True Soft
@Andrzej because in the example above he's not dealing with numbers in both cases. One is an iterable, the other is an index into an array. This illustrates iterating two different values at the same time (he would replace the `for` loop with the `while(itr.hasnext())`).
glowcoder