ComputerScienceExpert

(11)

$18/per page/

About ComputerScienceExpert

Levels Tought:
Elementary,Middle School,High School,College,University,PHD

Expertise:
Applied Sciences,Calculus See all
Applied Sciences,Calculus,Chemistry,Computer Science,Environmental science,Information Systems,Science Hide all
Teaching Since: Apr 2017
Last Sign in: 103 Weeks Ago, 3 Days Ago
Questions Answered: 4870
Tutorials Posted: 4863

Education

  • MBA IT, Mater in Science and Technology
    Devry
    Jul-1996 - Jul-2000

Experience

  • Professor
    Devry University
    Mar-2010 - Oct-2016

Category > Programming Posted 09 May 2017 My Price 11.00

public String toString()

In the Assignment #10, you are given three files Assignment10.java, LinkedList.java, and ListIterator.java. You will need to add additional methods in the LinkedList class in the LinkedList.java file. The LinkedList will be tested using strings only.

Specifically, the following methods must be implemented in the LinkedList class:
(You should utilize listIterator() method already defined in the LinkedList class to obtain its LinkedListIterator object, and use the methods in the LinkedListIterator class to traverse from the first element to the last element of the linked list to define the following methods.)

1.
    public String toString()

The toString method should concatenate strings in the linked list, and return a string of the following format:

{ Apple Banana Melon Orange }

Thus it starts with "{" and ends with "}", and there is a space between strings and "{" or "}". If the list is empty, it returns "{ }" with a space in between.

2.
    public boolean isEmpty()

The isEmpty method returns true of the linked list is empty, false otherwise.

3.
    public void addElement(Object element)

The addElement adds the parameter element at the parameter in the linked list in alphabetical order. For instance, if the linked list contains {Apple, Banana, Grape}, and a user tries to add "Carrot", then it should be added as:
{Apple, Banana, Carrot, Grape}.

4.
    public Object removeElement(int index)

The removeElement removes the string (Object) at the parameter index and returns it. Note that this index starts with 0 just like array indices. For instance, if the linked list contains {Apple, Banana, Carrot, Grape} and the parameter index is 3, then "Grape" should be remove. If the parameter index is larger or smaller than the existing indices, it should throw an object of the IndexOutOfBoundsException class (and the content of the linked list should remain unchanged).

5.
    public Object getElement(int index)

The getElement searches the string (Object) at the parameter index and returns it. Note that this index starts with 0 just like array indices. For instance, if the linked list contains {Apple, Banana, Carrot, Grape} and the parameter index is 3, then "Grape" will be returned. If the parameter index is larger or smaller than the existing indices, it should throw an object of the IndexOutOfBoundsException class (and the content of the linked list should remain unchanged).

6.
public void searchAndReplace(Object oldString, Object newString)

The searchAndReplace method searches all occurrences of the first parameter string (object) in the list, and replaces them with the second parameter string (object). If the parameter string does not exist in the linked list, then the linked list content will not change.

7.
public int indexOfLast(Object searchString)

The indexOfLast searches the parameter string (object) with the largest index, and returns its index. If the parameter string does not exist in the linked list, then it should return -1.
For instance, if the linked list contains { Apple Banana Banana Orange }, then after calling this method with the parameter "Banana", then it should return 2, which is the index of later Banana.

public class Assignment10
{
   public static void main(String[] args)
   {
      char input1;
       String inputInfo = new String();
       int operation2;
       String line = new String();

       //create a linked list to be used in this method.
       LinkedList list1 = new LinkedList();

       try
        {
         // print out the menu
         printMenu();

         // create a BufferedReader object to read input from a keyboard
         InputStreamReader isr = new InputStreamReader (System.in);
         BufferedReader stdin = new BufferedReader (isr);

         do
          {
           System.out.print("What action would you like to perform?n");
           line = stdin.readLine().trim();  //read a line
           input1 = line.charAt(0);
           input1 = Character.toUpperCase(input1);

           if (line.length() == 1)   //check if a user entered only one character
            {
             switch (input1)
              {
               case 'A':   //Add String
                 System.out.print("Please enter a string to add:n");
                 String str1 = stdin.readLine().trim();
                 list1.addElement(str1);
                 break;
               case 'G':   //Get a String at a certain index
                 System.out.print("Please enter an index of a string to get:n");
                 inputInfo = stdin.readLine().trim();
                 int getIndex = Integer.parseInt(inputInfo);
                 try
                  {
                   String getString = list1.getElement(getIndex);
                   System.out.print("The string at the index " + getIndex + " is " 
                                    + getString + "n");    
                  }
                 catch(IndexOutOfBoundsException ex)
                  {
                   System.out.print("The index is not validn");
                  }
                 break;
               case 'E':   //Check if the linked list is empty
                 boolean empty = list1.isEmpty();
                 if (empty)
                  System.out.print("The linked list is emptyn");
                 else
                  System.out.print("The linked list is not emptyn");
                 break;
               case 'I':   //Get the last index of a given String
                 System.out.print("Please enter a string to search:n");
                 String str2 = stdin.readLine().trim();
                 int searchIndex = list1.indexOfLast(str2);
                 if (searchIndex != -1)
                  System.out.print("The index of the last " + str2 + " is " + searchIndex
                                   + "n");
                 else
                  System.out.print("The string " + str2 
                                 + " does not exist in the linked listn");
                 break;
               case 'L':   //List Strings
                 System.out.print(list1.toString());
                 break;
               case 'Q':   //Quit
                 break;
               case 'R':  //Remove a String
                 System.out.print("Please enter an index of a string to remove:n");
                 inputInfo = stdin.readLine().trim();
                 int removeIndex = Integer.parseInt(inputInfo);
                 try
                  {
                   String removeString = (String) list1.removeElement(removeIndex);
                   System.out.print("The string at the index " + removeIndex + " was "   
                                    + removeString + " and was removedn");
                  }
                 catch(IndexOutOfBoundsException ex)
                  {
                   System.out.print("The index is not validn");
                  }
                 break;
               case 'S':   //Search and Replace
                 System.out.print("Please enter a string to replace:n");
                 String original = stdin.readLine().trim();
                 System.out.print("Please enter a string used to replace with:n");
                 String newStr = stdin.readLine().trim();
                 list1.searchAndReplace(original, newStr);
                 break;
               case '?':   //Display Menu
                 printMenu();
                 break;
               default:
                 System.out.print("Unknown actionn");
                 break;
              }
           }
          else
           {
             System.out.print("Unknown actionn");
            }
          } while (input1 != 'Q' || line.length() != 1);
        }
       catch (IOException exception)
        {
          System.out.print("IO Exceptionn");
        }
    }

    /** The method printMenu displays the menu to a user **/
    public static void printMenu()
     {
       System.out.print("ChoicettActionn" +
                        "------tt------n" +
                        "AttAdd Stringn" +
                        "GttGet Stringn" +
                        "EttCheck if Emptyn" +
                        "IttIndex of Last Stringn" +
                        "LttList Stringsn" +
                        "QttQuitn" +
                        "RttRemove Stringn" +
                        "SttSearch and Replacen" +
                        "?ttDisplay Helpnn");
    } //end of printMenu()
}
public class LinkedList
{
   //nested class to represent a node
   private class Node
   {
          public Object data;
          public Node next;
   }

   //only instance variable that points to the first node.
   private Node first;

   // Constructs an empty linked list.
   public LinkedList()
   {
      first = null;
   }


   // Returns the first element in the linked list.
   public Object getFirst()
   {
      if (first == null)
       {
         NoSuchElementException ex
             = new NoSuchElementException();
         throw ex;
       }
      else
         return first.data;
   }

   // Removes the first element in the linked list.
   public Object removeFirst()
   {
      if (first == null)
       {
         NoSuchElementException ex = new NoSuchElementException();
         throw ex;
       }
      else
       {
         Object element = first.data;
         first = first.next;  //change the reference since it's removed.
         return element;
       }
   }

   // Adds an element to the front of the linked list.
   public void addFirst(Object element)
   {
      //create a new node
      Node newNode = new Node();
      newNode.data = element;
      newNode.next = first;
      //change the first reference to the new node.
      first = newNode;
   }

   // Returns an iterator for iterating through this list.
   public ListIterator listIterator()
   {
      return new LinkedListIterator();
   }


   /*********************************************************
   Add your methods here
   *********************************************************/


   //nested class to define its iterator
   private class LinkedListIterator implements ListIterator
   {
      private Node position; //current position
      private Node previous; //it is used for remove() method

      // Constructs an iterator that points to the front
      // of the linked list.

      public LinkedListIterator()
      {
         position = null;
         previous = null;
      }

     // Tests if there is an element after the iterator position.
     public boolean hasNext()
      {
         if (position == null) //not traversed yet
          {
             if (first != null)
                return true;
             else
                return false;
          }
         else
           {
              if (position.next != null)
                 return true;
              else
                 return false;
           }
      }

      // Moves the iterator past the next element, and returns
      // the traversed element's data.
      public Object next()
      {
         if (!hasNext())
          {
           NoSuchElementException ex = new NoSuchElementException();
           throw ex;
          }
         else
          {
            previous = position; // Remember for remove

            if (position == null)
               position = first;
            else
               position = position.next;

            return position.data;
          }
      }

      // Adds an element before the iterator position
      // and moves the iterator past the inserted element.
      public void add(Object element)
      {
         if (position == null) //never traversed yet
         {
            addFirst(element);
            position = first;
         }
         else
         {
            //making a new node to add
            Node newNode = new Node();
            newNode.data = element;
            newNode.next = position.next;
            //change the link to insert the new node
            position.next = newNode;
            //move the position forward to the new node
            position = newNode;
         }
         //this means that we cannot call remove() right after add()
         previous = position;
      }

      // Removes the last traversed element. This method may
      // only be called after a call to the next() method.
      public void remove()
      {
         if (previous == position)  //not after next() is called
          {
            IllegalStateException ex = new IllegalStateException();
            throw ex;
          }
         else
          {
           if (position == first)
            {
              removeFirst();
            }
           else
            {
              previous.next = position.next; //removing
            }
           //stepping back
           //this also means that remove() cannot be called twice in a row.
           position = previous;
      }
      }

      // Sets the last traversed element to a different value.
      public void set(Object element)
      {
         if (position == null)
          {
            NoSuchElementException ex = new NoSuchElementException();
            throw ex;
          }
         else
          position.data = element;
      }
   } //end of LinkedListIterator class
} //end of LinkedList class
public interface ListIterator
{
   //Move Moves the iterator past the next element.
   Object next();

   // Tests if there is an element after the iterator position.
   boolean hasNext();

   // Adds an element before the iterator position
   // and moves the iterator past the inserted element.
   void add(Object element);


   // Removes the last traversed element. This method may
   // only be called after a call to the next() method.
   void remove();

   // Sets the last traversed element to a different value.
   void set(Object element);
}

Attachments:

Answers

(11)
Status NEW Posted 09 May 2017 06:05 AM My Price 11.00

-----------

Not Rated(0)