1

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.

4
  • 1
    that doesn't look like java (with the HTML tags interspersed)... could you elaborate on your programming environment? Commented Aug 12, 2010 at 16:27
  • 1
    It looks like you only need 1 loop. Commented Aug 12, 2010 at 16:28
  • 1
    AND THEY'RE OFF!! Initially they are neck-and-neck. This is going to shape up to be a great race! Commented Aug 12, 2010 at 16:31
  • 1
    Don't use raw types in new code: stackoverflow.com/questions/2770321/… Commented Aug 12, 2010 at 16:32

3 Answers 3

9

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).

Sign up to request clarification or add additional context in comments.

3 Comments

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: Good insight, but parallel iteration is mentioned (as limitation of for-each) both in language guide (download-llnw.oracle.com/javase/1.5.0/docs/guide/language/…) and Effective Java 2nd Edition, Item 46: Prefer for-each loops to traditional for loops.
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.
2

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)
     }
 }

4 Comments

You should change rCount to index in Printed row... statement.
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] Printed row...0 DA Email from [email protected] Printed row...0 DA Email from [email protected] Printed row...0
@Pritish: Doh - that "i++" shouldn't be there at all. It shouldn't be printing "row 0" multiple times though.
Sorry, I'd int index = 0 declared inside the while loop() that was causing the problem. Have sorted that out.Thanks for your help!
0

"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++;
}

3 Comments

Why bother with the j counter in the final example, when by definition you want it to be identical to i at all times?
It is possible to put j in the for statement, like this: for (i = 0, j = 0; i < 3; i++, j++) {
@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())).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.