/************************************************************************* * Name: * NetID: * Precept: * * Description: This class allows you to do and undo two String * operations: append() and replace(). * * Examples: * % java LineEditSolution * COS ROCKS * COS ROX * COS ROX!! * COS ROX * COS ROCKS *************************************************************************/ public class LineEditSolution { Stack history; // push previous states of current String current; // current String, not in history // create a new LineEdit with given initial text public LineEditSolution(String text) { history = new Stack(); current = text; } // get the current state of the editor public String toString() { return current; } // add the given text at the end of the line public void append(String text) { history.push(current); current = current + text; } // replace all occurrences of "from" with "to" public void replace(String from, String to) { history.push(current); current = current.replace(from, to); } // undo the latest append/replace operation that hasn't already been undone public void undo() { if (!history.isEmpty()) current = history.pop(); } // test client public static void main(String[] args) { LineEditSolution line = new LineEditSolution("COS ROCKS"); System.out.println(line); line.replace("CKS", "X"); System.out.println(line); line.append("!!"); System.out.println(line); line.undo(); System.out.println(line); line.undo(); System.out.println(line); } }