เลิกทำการกระทำล่าสุดใน Text Editor
Text editor หลายตัวช่วยให้ผู้ใช้ย้อนกลับไปดูการเปลี่ยนแปลงและแทรกคำที่ขาดหายไปได้ตามต้องการ การใช้ ListIterator ทำให้สามารถวนย้อนกลับผ่านรายการการกระทำ และแทรกการแก้ไขในตำแหน่งที่ต้องการได้
ในแบบฝึกหัดนี้ จะวนซ้ำผ่านรายการคำแบบย้อนกลับ และหากพบคำว่า "error" จะแทรก correction ไว้ก่อนหน้าคำนั้น เพื่อจำลองการทำงาน Undo ใน Text Editor
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Input/Output และ Streams ใน Java
คำแนะนำการฝึกหัด
- สร้างออบเจ็กต์
ListIteratorสำหรับรายการtextHistoryโดยเริ่มจากท้ายรายการ - ตรวจสอบว่ายังมีองค์ประกอบก่อนหน้าเหลืออยู่ในรายการ
textHistoryหรือไม่ - ดึงองค์ประกอบก่อนหน้าและเลื่อน
ListIteratorไปข้างหลัง - แทรกองค์ประกอบใหม่
correctionไว้ก่อนองค์ประกอบerror
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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);
}
}