-1

I want iterate in Java trough an increasing number of elements, this the code i was thinking about but I'm not sure about it:

for (int i = 0; i<=maxSomething; i++) {  
    action(i);

    for(String a : ArrayOfString)
       otherActions();
}

What i want to do is that:

  • i = 0: perform action(0)
  • i = 1: perform action(0) and action(1)
  • i = 2: perform action(0), action(1) and action(2)
  • i<=maxSomething: perform all actions

How can I do this?

4

4 回答 4

5

You'll need nested loops:

for (int i = 0; i <= maxSomething; i++) {
    for (int j = 0; j <= i; j++) {
        action(j);
    }
}
于 2013-10-18T07:02:03.480 回答
0

Have a nested for loop, iterating a new variable, j, from 0 to i, containing action(j). This will get called from 0 to i.

于 2013-10-18T07:03:54.193 回答
-1

Update

I saw the below recursive function only gives result for one sequence of actions.

public static void recursive (int i) {
    action(i);
    if (i > 0) 
        recursive(--i);
}

So instead use an nested loop,it's preferred.

Recursion bloats the stack.

于 2013-10-18T07:10:00.173 回答
-2

Does the action change after each iteration, action(0) once done- can this be reused when called in the next loop run ? If yes, you should use recursion here.

于 2013-10-18T07:06:01.487 回答