Undo last action in a text editor
Many text editors allow users to navigate backward through changes and insert missing words when needed. Using ListIterator
, you can move backward through a list of actions and insert corrections where necessary.
In this exercise, you will traverse a list of words in reverse, and if you find "error", you will insert correction
before it, simulating an undo operation in a text editor.
This exercise is part of the course
Input/Output and Streams in Java
Exercise instructions
- Create a
ListIterator
object for thetextHistory
list, starting from the end. - Check if more previous elements are available in
textHistory
list. - Retrieve previous element and move
ListIterator
backward - Insert new element
correction
before elementerror
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.util.ArrayList;
import java.util.ListIterator;
public class TextEditorUndo {
public static void main(String[] args) {
ArrayList textHistory = new ArrayList<>();
textHistory.add("Hello");
textHistory.add("error");
textHistory.add("world");
// Create ListIterator starting from the end of the list
ListIterator it = textHistory.________(textHistory.____());
// Check if more elements available in reserve order
while (____.____()) {
// Retrieve previous element
String word = ____.____();
if (word.equals("error")) {
// Insert "correction" before "error"
____.____("correction");
}
}
System.out.println(textHistory);
}
}