tags:

views:

117

answers:

2

Hi guys

i am looping through a list of strings, in psudocode this is how

for (each node in my list)
    if the node.getBooleanVariable == true
        add one to my counter
    else 
        take one away from my counter
    if my counter = another counter 
       print node.getStringVariable() //THIS IS WHERE I AM STUCK

here i want to concatenate the string from node.getStringVariable() with the node whos next boolean element is a false one. Does that make it any clearer?

thanks

A: 

If your logic needs to "look forward" in your list while iterating through it to find the next false node, then a for-each may not be appropriate. That's because a for-each only lets you look at the current element of the list at any given time. If you can share some background information about the loop's requirements, someone may be able to suggest some pseudocode that works without need to look forward.

If it turns out that you do have to look forward, you may have to use a standard for loop to get more control.

for (int i = 0; i < myList.size(); i++) {
   Node node = myList.get(i);
   // oh, I have to look forward?  use another for loop
   for (int j = i + 1; j < myList.size(); j++) {
      Node forwardNode = myList.get(j);
      // do stuff with forwardNode
   }
}
Kaleb Brasee
this is how i started however the list i am working with does not have a size method so there is no way to determine its length, else this is the approach i would have taken ;)
timmy
So you are using a custom list instead of one of the built in Java lists, or an array? Was that part of the assignment?
Kaleb Brasee
+1  A: 

If your list of nodes is not too long, it would be clearer (in my opinion) to separate out the strings you need to concatenate into another list and then concatenate them at the end. For example:

for (each node in my list)
    if the node.getBooleanVariable == true
        add one to my counter
    else 
        take one away from my counter
    if my counter = another counter 
        concatList.add(node.getStringVariable())

for (each str in concatList)
    finalString += str

This will not be the most absolutely efficient approach, but it won't be bad. If your list is only a couple thousand elements you won't notice the overhead of creating a separate list. And I think it is a little easier to understand this way, but that is just personal opinion.

A. Levy