flwy_h flwy_h - 3 months ago 12
Java Question

Is it possible to undo last execution of a while loop?

Here is an example:

int i = 0;
while (i < 11) {
System.out.println(i);
list.add(i);
i++;
}


Output should be:

0
1
2
3
4
5
6
7
8
9
10


The arraylist should have the same values for each index but what if I don't want the 10?

Is it possible "undo" the last execution of the while loop considering the while loop cannot be modified?

I know it's simpler to just remove the last index of the arraylist but what if the execution wasn't as simple to undo (as is the case for my related problem)?

If not possible, would it be better to just modify the loop condition?
(for my problem different from this one, I'm stuck on how to modify the condition as it works perfectly except for the very last execution which modifies a whole bunch of different things that is not easy to undo as with the simple arraylist example here).

Answer

You'll always know the last index of the array (arrayList.size() - 1). But simply deleting the last item in an array isn't an "undo" but rather a postoperative modification.

There's not an "undo last iteration"-type feature.