开发者

for each loop help

开发者 https://www.devze.com 2022-12-13 05:09 出处:网络
i am looping through a list of strings, in psudocode this is how 开发者_StackOverflow for (each node in my list)

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

开发者_StackOverflow
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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消