Write a simple text editor, which stores and displays a string of characters using the positional list ADT, together with a cursor object that highlights a position in the string. The editor must support the following operations:
• left: Move cursor left one character (do nothing if at beginning).
• right: Move cursor right one character (do nothing if at end).
• insert c: Insert the character c just after the cursor.
• delete: Delete the character just after the cursor (if not at end).
PROGRAM CODE:
import java.util.*;
public class TextEditor {
private PositionalList<Character> text;
private Position<Character> cursor;
public TextEditor() {
text = new LinkedPositionalList<>();
cursor = null;
}
// Move the cursor left one character
public void left() {
if (cursor != null && cursor != text.first())
cursor = text.before(cursor);
}
// Move the cursor right one character
public void right() {
if (cursor != null && cursor != text.last())
cursor = text.after(cursor);
}
// Insert a character just after the cursor
public void insert(char c) {
if (cursor == null) {
cursor = text.addFirst(c);
} else {
cursor = text.addAfter(cursor, c);
}
}
// Delete the character just after the cursor
public void delete() {
if (cursor != null) {
Position<Character> next = text.after(cursor);
if (next != null)
cursor = text.remove(next);
}
}
// Display the text
public void displayText() {
for (Character c : text)
System.out.print(c);
System.out.println();
}
public static void main(String[] args) {
TextEditor editor = new TextEditor();
editor.insert('H');
editor.insert('e');
editor.insert('l');
editor.insert('l');
editor.insert('o');
editor.displayText(); // Output: Hello
editor.left();
editor.left();
editor.displayText(); // Output: Hel|lo
editor.right();
editor.insert(' ');
editor.insert('W');
editor.insert('o');
editor.insert('r');
editor.insert('l');
editor.insert('d');
editor.displayText(); // Output: Hel Wor|ld
editor.delete();
editor.displayText(); // Output: Hel Wo|ld
}
}
OUTPUT OF THE PROGRAM CODE:
Hello
Hel|lo
Hel Wor|ld
Hel Wo|ld