Question

You are to write a Java program that emulates an “undo” operation in programs like Word...

  1. You are to write a Java program that emulates an “undo” operation in programs like Word processors.
  2. You will need to use the proper data structures as you see fit.
  3. Specifically, you will create a data type called, DocumentBuffer, that acts as edit buffer & keeps a list of Line data type.
  4. To keep it simple, DocumentBuffer will have these editing operations: add a Line and remove a Line.
  5. DocumentBuffer will store its state during any edits. It will need a help from another data type, called CareTaker.
  6. Any time you make an edit, e.g. add a line or delete a line, DocumentBuffer will ask, i.e. use the methods of, the CareTaker to store its current state. DocumentBuffer state is defined as its lineBuffer list that you add or delete lines.
  7. DocumentBuffer will expose a public method called undo() that will restore its state to the last known state before making any changes. It will basically restore its state to the last known state prior to making any edits. It will always undo the last operation and you can keep calling undo to restore prior states, until there are no more undo to execute. This indicates that you have reached the initial state.
  8. The following scenario demonstrate how this works. The lines I am adding or deleting are simple strings like ‘line 1’, ‘line 2’, etc. Lines like ‘inserting …’, ‘removing…’, ‘undo…’ are just println() statements from the test driver to show what I am doing and they are not part of the buffer. Also, the prefix like ‘1>, 2>’, etc. are line numbers associated with line number. Lines with “***********” is just a separator between each state, again printed from the test driver.

inserting new line...

1> line 1

***************

inserting new line...

1> line 1

2> line 2

***************

inserting new line...

1> line 1

2> line 2

3> line 3

***************

inserting new line...

1> line 1

2> line 2

3> line 3

4> line 4

***************

removing a line...

1> line 1

3> line 3

4> line 4

***************

undo last operation...

1> line 1

2> line 2

3> line 3

4> line 4

***************

undo last operation...

1> line 1

2> line 2

3> line 3

Program Specifications

  1. DocumentBuffer class—a simple edit manager that stores lines (just a list of strings), exposes edit methods, undo operations and provides methods to store and restore its internal state.
    1. Data members:
      • private List lineBuffer;
      • private final CareTaker ct;
    2. Methods:
      • public DocumentBuffer(CareTaker ct){}—constructor that requires CareTaker object and initializes its ct data mamber. You also need to initialize lineBuffer and use ct to store its initial state (more on CareTaker specs below).
      • public boolean addLine(Line line){}—adds a line to the line buffer. Just add the line to the end of the buffer. Must save state before adding a new a line. Return true if all goes well, false otherwise.
      • public int removeLine(int lineno){}—removes a line based on its line number. Must save state before removing a new a line. Return line number that was removed.
      • public String toString(){}—this method will dump all lines in the buffer in the manner I showed in the sample output above.
      • private Memento saveStateToMemento(){}—this method will save the current state using a Memento object (specs to follow). Return the Memento object just created.
      • private void restoreStateFromMemento(Memento mem){}—this method will restore the state from a Memento object passed to it.
      • public boolean undo(){}—this the public method that you will use to undo last operation. It will need the help of CareTaker to retrieve last Memento object stored and then calls restoreStateFromMemento() passing it the Memento object just retrieved from the CareTaker.
  2. Line class—a class that represents the edit lines that DocumentBuffer manages.
    1. Data members:
      • private String text;
      • private int lineno;
    2. Methods:
      • public Line(String text, int lineno){}— initializer constructor
      • public String toString(){}—returns a string representation in the manner shown above in the sample output.
  3. Memento class—a class that stores/restore the states of DocumentBuffer. Think of it as object that remembers what you asked it to remember, hence the name Memento.
    1. Data members:
      • private List state;
    2. Methods:
      • public Memento(List state){}—stores state passed to it.
      • public List getState(){}—get state stored in this object.
  4. CareTaker class—is stack that stores and retrieves Memento objects.
    1. Data members:
      • private Deque mStack; // use Deque<> as a stack
    2. Methods:
      • public void add(Memento state){}—push Memento object passed onto a stack
      • public Memento get(){}—pops last Memento object from the stack
0 0
Add a comment Improve this question Transcribed image text
Answer #1

There is no screenshot to attach as the driver program was not part of the specification.

please rate if you find the answer satisfactory and do comment if you face any issues.

DocumentBuffer

package undo;

import java.util.ArrayList;
import java.util.List;

public class DocumentBuffer {
   private List<Line> lineBuffer;
   private final CareTaker ct;

   public DocumentBuffer (CareTaker ct) {

       this.ct = ct;
       this.lineBuffer = new ArrayList<Line>();
       ct.add(new Memento(this.lineBuffer));
   }

   public boolean addLine(Line line) {

       try {
           saveStateToMemento();
           this.lineBuffer.add(line);
           System.out.println("Adding Line...");
           return true;
       } catch (Exception e) {
           return false;
       }

   }

   public int removeLine(int lineno) {
       try {
           saveStateToMemento();
           this.lineBuffer.remove(lineno);
           System.out.println("Removing Line...");
           return lineno;
       } catch (Exception e) {
           return -1;
       }
   }

   public String toString() {
       StringBuilder sb = new StringBuilder();
       for (Line l : this.lineBuffer) {
           sb.append(l.toString() + "\n");
       }
       return null;
   }

   private Memento saveStateToMemento() {
       Memento mem = new Memento(this.lineBuffer);
       ct.add(mem);
       return mem;
   }

   private void restoreStateFromMemento(Memento mem) {

       this.lineBuffer = mem.getState();
   }

   public boolean undo() {
       try {
           restoreStateFromMemento(this.ct.get());
           return true;
       } catch (Exception e) {
           return false;
       }
   }
}

Line

package undo;

public class Line {

   private String text;
   private int lineno;

   public Line (String text, int lineno) {

       this.text = text;
       this.lineno = lineno;
   }

   public String toString() {
       return this.lineno + "> " + this.text;
   }
}

CareTaker

package undo;

import java.util.Deque;
import java.util.LinkedList;

public class CareTaker {

   private Deque mStack; // use Deque<> as a stack

   public CareTaker () {
       super();
       mStack = new LinkedList<Memento>() {};
   }

   public void add(Memento state) {
       mStack.add(state);
   }

   public Memento get() {
       return (Memento) mStack.pop();
   }
}

Memento

package undo;

import java.util.ArrayList;
import java.util.List;

public class Memento {

   private List state;

   public Memento () {
       this.state = new ArrayList<ArrayList<Line>>();
   }

   public Memento (List state) {
       this.state = new ArrayList<ArrayList<Line>>(state);
   }

   public List getState() {
       return (List) this.state.get(this.state.size() - 1);
   }
}

Add a comment
Know the answer?
Add Answer to:
You are to write a Java program that emulates an “undo” operation in programs like Word...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • You are to write a program that emulates an “undo” operation in programs like Word processors....

    You are to write a program that emulates an “undo” operation in programs like Word processors. 2. You will need to use the proper data stuctures as you see fit. 3. Specifically, you will create a data type called, DocumentBuffer, that acts as edit buffer & keeps a list of Line data type. 4. To keep it simple, DocumentBuffer will have these editing operations: add a Line and remove a Line. 5. DocumentBuffer will store its state during any edits....

  • C# ONLY C# ONLY C# ONLY In this assignment you will implement the undo feature for a simple calculator. The undo feature...

    C# ONLY C# ONLY C# ONLY In this assignment you will implement the undo feature for a simple calculator. The undo feature must be implemented using a generic or template-based Stack data structure. You may utilize language supplied libraries (e.g. java.util.stack) or a stack implementation of your own design. No third-party downloads or software installs are allowed. The undo feature must allow for an unlimited number of undo operations. If the user attempts to perform an undo operation and the...

  • JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array...

    JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array storing elements in the list • topOfStack: an int value representing the location of the stack top in the array • INITIAL_CAPACITY: the default capacity of the stack public class ArrayBasedStack <E> { private E[] data; private int topOfStack; private static final int INITIAL_CAPACITY = 5; } Add a constructor that will initialize the stack with a user-defined initial capacity. The top of the...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private...

  • 22.7 Lab: Word ladder Write a word ladder program. Read this wikipedia article that describes what...

    22.7 Lab: Word ladder Write a word ladder program. Read this wikipedia article that describes what a word ladder is: Word Ladder Your program must use a list to store the dictionary of words and then use stacks of strings and a queue of these stacks to solve for and output the word ladder. You are required to use the Standard Template Library (STL) list, stack, and queue. You must implement the WordLadder class. The class is declared in WordLadder.h....

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

  • solve this Q in java languege Write a method that return DoublyLinkedList as reversed string For...

    solve this Q in java languege Write a method that return DoublyLinkedList as reversed string For example: If the elements of a list is 1, 2, 3, 4, 5, 6 the reverse string should be 6, 5, 4, 3, 2, 1 implement reverse method you have two steps: 1- you should start traversing from the last element of DoublyLinkedList (the previous of the trailer) 2- you should add the element inside each node to string don't forget the space in...

  • Modify the following given Java program. You are expected to modify the supplied Exercise1.java to print...

    Modify the following given Java program. You are expected to modify the supplied Exercise1.java to print just the last lines of each paragraph in HTML format. Copy and paste the Sample input on the console then print the Expected output. import java.util.Scanner; public class Exercise1 { /** A simple static string for HTML & table header. */ private static final String HTMLHeader = "<!DOCTYPE html>\n" + " <html>\n" + " <head>\n" + " <title>CSE: Exercise 1</title>\n" + " </head>\n" +...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT