開始使用免費開始

更新通訊錄中的姓名

某個聯絡人管理系統會把姓名儲存在清單中。當需要更新姓名(例如更正拼字錯誤)時,你可以使用 ListIterator 在走訪的同時修改項目。

來自 java.util 的所有必要類別都已為你匯入。

本練習屬於課程

Java 的輸入/輸出與串流

檢視課程

練習說明

  • contacts 清單建立一個 ListIterator 物件。
  • 在 while 迴圈的條件中,檢查 contacts 清單中是否還有元素可用。
  • 取得下一個元素。
  • 如果姓名是 Jon,就把它改成 John

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class ContactUpdater {
    public static void main(String[] args) {
        ArrayList contacts = new ArrayList<>();
        contacts.add("Alice");
        contacts.add("Jon");
        contacts.add("Charlie");

        // Create ListIterator for the contacts list
        ListIterator it = contacts.____();

        // Check if more elements are available
        while (____.____()) {
        	// Retrieve next element
            String name = ____.____();
            if (name.equals("Jon")) {
                // Update element to "John"
                ____.____("John");
            }
        }

        System.out.println(contacts);
    }
}
編輯並執行程式碼