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.
Cet exercice fait partie du cours
Input/Output and Streams in Java
Instructions
- Create a
ListIteratorobject for thetextHistorylist, starting from the end. - Check if more previous elements are available in
textHistorylist. - Retrieve previous element and move
ListIteratorbackward - Insert new element
correctionbefore elementerror
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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);
}
}