開始使用免費開始

在文字編輯器中復原上一個動作

許多文字編輯器允許使用者向後瀏覽變更,並在需要時插入遺漏的字詞。使用 ListIterator,你可以在動作清單中向後移動,並在必要時插入更正。

在本練習中,你將反向遍歷單字清單;如果發現「error」,你會在它前面插入 correction,以模擬文字編輯器中的復原操作。

本練習屬於課程

Java 的輸入/輸出與串流

檢視課程

練習說明

  • 建立從清單尾端開始的 textHistoryListIterator 物件。
  • 檢查 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);
    }
}
編輯並執行程式碼