开始使用免费开始使用

在文本编辑器中撤销上一步操作

许多文本编辑器允许用户向后浏览更改,并在需要时插入缺失的单词。使用 ListIterator,您可以在操作列表中向后移动,并在必要时插入更正。

在本练习中,您将反向遍历一个单词列表;如果遇到 "error",就在它之前插入 correction,以模拟文本编辑器中的撤销操作。

本练习是课程的一部分

Java 中的输入/输出与流

查看课程

练习说明

  • textHistory 列表创建一个从末尾开始的 ListIterator 对象。
  • 检查 textHistory 列表中是否还有上一个元素可用。
  • 获取上一个元素,并使 ListIterator 向后移动。
  • 在元素 error 之前插入新元素 correction

交互式实操练习

通过完成这段示例代码来试试这个练习。

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 are available in reverse order
        while (____.____()) {
        	// Retrieve previous element
            String word = ____.____();
            if (word.equals("error")) {
                // Insert "correction" before "error"
                ____.____("correction");
            }
        }

        System.out.println(textHistory);
    }
}
编辑并运行代码