100 lines
2.7 KiB
Java
100 lines
2.7 KiB
Java
package encapsulation;
|
|
|
|
public class LineEditor {
|
|
|
|
private String text = "";
|
|
private int insertionIndex = 0;
|
|
|
|
/**
|
|
* Moves the insertion index to the left (if available)
|
|
*/
|
|
public void left() {
|
|
this.insertionIndex -= (this.insertionIndex != 0) ? 1 : 0;
|
|
}
|
|
|
|
/**
|
|
* Moves the insertion index to the right (if available)
|
|
*/
|
|
public void right() {
|
|
this.insertionIndex += (this.insertionIndex != this.text.length()) ? 1 : 0;
|
|
}
|
|
|
|
/**
|
|
* Inserts a string at the insertion index and shoves the insertionIndex behind the new text.
|
|
* @param s the string to insert
|
|
*/
|
|
public void insertString(String s) {
|
|
this.text = this.text.substring(0, this.insertionIndex)
|
|
+ s
|
|
+ this.text.substring(this.insertionIndex);
|
|
this.insertionIndex += s.length();
|
|
}
|
|
|
|
/**
|
|
* Removes the character to the left of the insertionIndex (if available)
|
|
*/
|
|
public void deleteLeft() {
|
|
if (this.insertionIndex != 0) {
|
|
this.text = this.text.substring(0, this.insertionIndex - 1)
|
|
+ this.text.substring(this.insertionIndex);
|
|
this.insertionIndex--;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Removes the character to the right of the insertionIndex (if available)
|
|
*/
|
|
public void deleteRight() {
|
|
if (this.insertionIndex != this.text.length())
|
|
this.text = this.text.substring(0, this.insertionIndex)
|
|
+ this.text.substring(this.insertionIndex + 1);
|
|
}
|
|
|
|
public String getText() {
|
|
return this.text;
|
|
}
|
|
|
|
public void setText(String s) {
|
|
if (this.insertionIndex > s.length())
|
|
this.insertionIndex = s.length();
|
|
this.text = s;
|
|
this.insertionIndex = s.length();
|
|
}
|
|
|
|
public int getInsertionIndex() {
|
|
return this.insertionIndex;
|
|
}
|
|
|
|
public void setInsertionIndex(int i) throws IllegalArgumentException {
|
|
if ( i < 0 || this.text.length() < i)
|
|
throw new IllegalArgumentException("The insertion index has to be inside the scope of the text");
|
|
this.insertionIndex = i;
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
return this.text.substring(0, this.insertionIndex)
|
|
+ "|"
|
|
+ this.text.substring(this.insertionIndex);
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
LineEditor lineeditor = new LineEditor();
|
|
lineeditor.setText("test");
|
|
System.out.println(lineeditor);
|
|
lineeditor.left();
|
|
System.out.println(lineeditor);
|
|
lineeditor.right();
|
|
System.out.println(lineeditor);
|
|
lineeditor.setInsertionIndex(2);
|
|
System.out.println(lineeditor);
|
|
lineeditor.deleteRight();
|
|
System.out.println(lineeditor);
|
|
lineeditor.deleteLeft();
|
|
System.out.println(lineeditor);
|
|
lineeditor.insertString("ex");
|
|
System.out.println(lineeditor);
|
|
}
|
|
|
|
}
|