Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Eclipse Understand the Problem You are going to parallel the development do

ID: 3668471 • Letter: J

Question

Java Eclipse

Understand the Problem

You are going to parallel the development done in a past lesson on inheritance where we constructed some base classes, StackNode and Stack, and derived  FloatNode andFloatStack from them. You can work best by referring to those modules all through the development of your program. These are the differences between what we did in the lesson and what you will do for your assignment.

Instead of a Stack data structure, you will create a Queue data structure. A Stack is last-in-first-out (LIFO). A Queue is first-in-first-out (FIFO). We'll use push_back() andremove_front(), instead of push() and pop(), as the names of our primary accessors.

Instead of deriving a FloatNode from the basic Node class, you will derive a CardNode from our Node.  CardNode will use the Card class of Weeks 1 and 2.

Instead of signaling a pop() error by returning a special value (STACK_EMPTY = Float.MIN_VALUE), we will be more sophisticated and throw our own home-madeQueueEmptyException in our remove_front() method. The client will catch it.

We will replace all instances of show() with the more professional toString(), and let only the client send results to the display.

Picturing Queues

The front member of Queue will, be the first or oldest Node in the queue, and it is the will be the least recent one added. The back will always point to the most recent one added to the end of the Queue. Say we have added Nodes N1, N2, N3 and N4, in that order. The Nodes would be linked (in your Queue) as follows:

The links of the next pointers look like the StackNode organization, with front and back sharing the role of our old top:

The back pointer, not shown above, points to N4

If we instantiated a new Node N5, and added it onto the Queue q, it would go in at the back, Here is the Queue, q, after a q.push_back(N5);

A couple links have to be changed to result in:

Note: the back has to be adjusted:

If we then removed an item from the Queue, using q.remove_front(), the picture would be:

The links now convey the following:

Note, the back may not have to be adjusted (but in one case, not shown, it will):

Of course, when you do this, you will only be changing a couple pointers in each operation (either near the back or near the front). Most of the nodes don't need to be touched inpush_back() and remove_front().

Phase 1: Base Classes Node and Queue

Base Class Node

You can use the same class for a base class that was used in the modules. However, I want you to give this class a different name. Call it Node (not QueueNode or StackNode, justNode).   Also, take heed to replace show() methods with toString() methods.

Base Class Queue

Next, do almost the same thing as we did with the Stack class, except make sure that this class works like a Queue, not a Stack. That means

We add items to the Queue using push_back() not push().  push() does not appear in our Queue class.

We retrieve items from the Queue using remove_front() not pop().  pop() does not appear in our Queue class.

remove_front() removes and returns the oldest item in the Queue. This is different from pop() which removed and returned the youngest item in the Queue.

remove_front() throws a QueueEmptyException exception if the queue is empty. You will define this exception.

Provide a toString() method produces a String of all the items in the Queue from oldest to youngest.

Instead of one Node pointer member, top, you'll need two Node pointer members, and neither should be called top (since top is not meaningful in a Queue). Instead call themfront and back.

Phase 2: Intermediate Step - Check Your Base Classes

Once you have written these two classes, write a simple test main() just like I did in the modules - show a run that displays some (generic node)s. Test the Queue's toString()method and also build a simple loop in your main() to remove and display nodes as they are removed.   Compare the output of these two techniques -- they should be similar. You will not hand this in. It is just for your use in developing the full program. Test your QueueEmptyException.

push_back() and remove_front() will be slightly more complicated than push() and pop() because you have two pointers, front and back, to manage. This may take some time and debugging. Test it carefully. Even after you get it to work, you may find that it still needs debugging later, since your "(generic node)" screen results won't tell you if things are coming off in the correct order. You won't know that until you have real data in your Nodes. That's the next part.

Phase 3: Derived Classes CardNode and CardQueue

Deriving from Node

Now comes the fun. Derive a class from Node, CardNode. This will contain one additional member, just like the FloatNode did. However, instead of that additional member being afloat it will be a Card. For this, you'll need to include the Card class of the first or second week.

Override the toString() method of the generic Node class to return the specific type of data. The important thing here is to not do any work - you let your Card class stringize itself through its, already defined, toString() method.

Deriving from Queue

Derive CardQueue from Queue, and, just like we did in the modules, write methods that let you add actual  Cards onto each of the Queue.

In your client, push_back() a bunch of cards, toString() the queue to the screen to see that this is working, then in a loop, remove_front() items displaying them as you do. Go "too far" so that you attempt to remove_front() from an empty queue and see that you are catching the exception.

Do not use collections or generics for this assignment.

Explanation / Answer


// import necessary classes
import java.lang.Exception;

public class HelloWorld
{
   public static void main(String[] args)
   {
      // create bunch of cards
      createLine(80, "-");
      System.out.println("Create Cards");
    
      Card c0 = new Card('T', Card.Suit.spades);
      Card c1 = new Card('J', Card.Suit.clubs);
      Card c2 = new Card('Q', Card.Suit.diamonds);
      Card c3 = new Card('K', Card.Suit.hearts);
      Card c4 = new Card('A', Card.Suit.spades);
    
      createLine(80, "-");
      System.out.println("Add Cards to the CardQueue");
    
      CardQueue cq = new CardQueue();
    
      // add the cards
      cq.addCard(c0);
      cq.addCard(c1);
      cq.addCard(c2);
      cq.addCard(c3);
      cq.addCard(c4);
    
      createLine(80, "-");
      System.out.println("Show the whole queue:");
    
      // show the whole queue
      System.out.println(cq.toString());
    
      createLine(80, "-");
      System.out.println("Remove cards one by one, while printing the "
            + "returned card. removing cards for ten times:");
    
      // removing the cards
      for (int i = 0; i < 10; i++)
      {
         try
         {
            System.out.println(cq.removeCard());
         }
         catch (QueueEmptyException e) // catch the error
         {
            System.out.println("[Catched an error exception]");
         }
      }
    
      createLine(80, "-");
      System.out.println("Program shutted down");
      createLine(80, "-");
   }

   /**
    * this method is just to make the program look "beautiful"
    *
    * @param length the length of the line
    * @param shape the shape of the caption
    */
   private static void createLine(int length, String shape)
   {
      for (int counter = 0; counter < length; counter += 1)
      {
         System.out.print(shape);
      }
   }
}

/**
* the Node class*/
class Node
{
   // member data that points another Node
   protected Node next;

   // constructor
   public Node()
   {
      next = null;
   }

   /**
    * return the string state of the node
    */
   public String toString()
   {
      return "[Basic Node] ";
   }
}

/**
* the Queue class*/
class Queue
{
   // pointer to first node in queue
   private Node head;
   private Node tail;

   // constructor
   Queue()
   {
      head = null;
      tail = null;
   }

   /**
    * add a node to the queue. put it as the tail of the queue.
    *
    * @param newNode as the intended node
    * @return true if success, false otherwise
    */
   public boolean add(Node newNode)
   {
      // emergency case
      if (newNode == null)
         return false;
    
      // set the initial head and tail, if the head is null
      if (head == null)
      {
         head = newNode;
         tail = newNode;
      }
    
      // set the new node to the tail of the queue
      tail.next = newNode;
      tail = newNode;
    
      return true;
   }

   /**
    * remove the first node of the queue.
    *
    * @return the head node
    * @throws QueueEmptyException if the queue is empty
    */
   public Node remove() throws QueueEmptyException
   {
      // create a temporary node
      Node tempNode;
    
      tempNode = head;
      if (head != null)
      {
         head = head.next;
         tempNode.next = null; // don't give client access to queue!
      }
      else
      {
         // throw a queue exception of the node is null
         throw new QueueEmptyException();
      }
    
      // return the previous head node
      return tempNode;
   }

   // toString method
   /**
    * return string representation of the queue
    */
   public String toString()
   {
      // declare local variables
      Node nodes;
      StringBuilder str = new StringBuilder();
    
      // Display all the nodes in the queue
      for (nodes = head; nodes != null; nodes = nodes.next)
      {
         str.append(nodes.toString());
      }
    
      // return the string
      return str.toString();
   }
}

/**
* an exception that specifically created for empty queue purpose*/
class QueueEmptyException extends Exception
{
   QueueEmptyException()
   {
      super("The Queue is Empty");
   }
}

class CardNode extends Node
{
   // additional data for subclass
   private Card card;

   // constructor
   CardNode(char value, Card.Suit suit)
   {
      super(); // constructor call to base class
      card = new Card(value, suit);
   }

   // accessor
   /**
    * get the card object from the CardNode objbect
    *
    * @return the card object
    */
   public Card getCard()
   {
      return card;
   }

   // toString method
   /**
    * stringize method
    */
   public String toString()
   {
      return card.toString() + " ";
   }
}

/**
* CardQueue class, extension of Queue class*/
class CardQueue extends Queue
{
   CardQueue()
   {
      super();
   }

   /**
    * add a card object to the queue
    *
    * @param value the cards value
    * @param suit the cards suit
    */
   public void addCard(char value, Card.Suit suit)
   {
      // create a new CardNode
      CardNode cNode = new CardNode(value, suit);
    
      // add the CardNode onto the Queue (base class call)
      super.add(cNode);
   }

   /**
    * overloaded version of addCard
    *
    * @param card the card object
    */
   public void addCard(Card card)
   {
      this.addCard(card.getVal(), card.getSuit());
   }

   /**
    * remove the first card, and return it
    *
    * @return the head card
    * @throws QueueEmptyException if there's an error
    */
   public Card removeCard() throws QueueEmptyException
   {
      // remove a card node
      CardNode cNode = (CardNode) remove();
    
      return cNode.getCard();
   }
}

// class Card ----------------------------------------------------------------
class Card
{
   // type and constants
   public enum State
   {
      deleted, active
   } // not bool because later we may expand

   public enum Suit
   {
      clubs, diamonds, hearts, spades
   }

   // for sort.
   public static char[] valueRanks =
      { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A', 'X' };
   static Suit[] suitRanks =
      { Suit.clubs, Suit.diamonds, Suit.hearts, Suit.spades };
   static int numValsInOrderingArray = 13; // maybe 14 if 'X' = Joker, or < 13

   // private data
   private char value;
   private Suit suit;
   State state;
   boolean errorFlag;

   // 4 overloaded constructors
   public Card(char value, Suit suit)
   {
      set(value, suit);
   }

   public Card(char value)
   {
      this(value, Suit.spades);
   }

   public Card()
   {
      this('A', Suit.spades);
   }

   // copy constructor
   public Card(Card card)
   {
      this(card.value, card.suit);
   }

   // mutators
   public boolean set(char value, Suit suit)
   {
      char upVal;            // for upcasing char
    
      // can't really have an error here
      this.suit = suit;
    
      // convert to uppercase to simplify
      upVal = Character.toUpperCase(value);
    
      // check for validity
      if (upVal == 'A' || upVal == 'K' || upVal == 'Q' || upVal == 'J'
            || upVal == 'T' || upVal == 'X' || (upVal >= '2' && upVal <= '9'))
      {
         errorFlag = false;
         state = State.active;
         this.value = upVal;
      }
      else
      {
         errorFlag = true;
         return false;
      }
    
      return !errorFlag;
   }

   public void setState(State state)
   {
      this.state = state;
   }

   // accessors
   public char getVal()
   {
      return value;
   }

   public Suit getSuit()
   {
      return suit;
   }

   public State getState()
   {
      return state;
   }

   public boolean getErrorFlag()
   {
      return errorFlag;
   }

   // stringizer
   public String toString()
   {
      String retVal;
    
      if (errorFlag)
         return "** illegal **";
      if (state == State.deleted)
         return "( deleted )";
    
      // else implied
    
      if (value != 'X')
      {
         // not a joker
         retVal = String.valueOf(value);
         retVal += " of ";
         retVal += String.valueOf(suit);
      }
      else
      {
         // joker
         retVal = "joker";
       
         if (suit == Suit.clubs)
            retVal += " 1";
         else if (suit == Suit.diamonds)
            retVal += " 2";
         else if (suit == Suit.hearts)
            retVal += " 3";
         else if (suit == Suit.spades)
            retVal += " 4";
      }
    
      return retVal;
   }

   public boolean equals(Card card)
   {
      if (this.value != card.value)
         return false;
      if (this.suit != card.suit)
         return false;
      if (this.errorFlag != card.errorFlag)
         return false;
      if (this.state != card.state)
         return false;
      return true;
   }

   // sort member methods
   public int compareTo(Card other)
   {
      if (this.value == other.value)
         return (getSuitRank(this.suit) - getSuitRank(other.suit));
    
      return (getValueRank(this.value) - getValueRank(other.value));
   }

   public static void setRankingOrder(char[] valueOrderArr, Suit[] suitOrdeArr,
         int numValsInOrderingArray)
   {
      int k;
    
      // expects valueOrderArr[] to contain only cards used per pack,
      // including jokers, needed to define order for the game environment
    
      if (numValsInOrderingArray < 0 || numValsInOrderingArray > 13)
         return;
    
      Card.numValsInOrderingArray = numValsInOrderingArray;
    
      for (k = 0; k < numValsInOrderingArray; k++)
         Card.valueRanks[k] = valueOrderArr[k];
    
      for (k = 0; k < 4; k++)
         Card.suitRanks[k] = suitOrdeArr[k];
   }

   public static int getSuitRank(Suit st)
   {
      int k;
    
      for (k = 0; k < 4; k++)
         if (suitRanks[k] == st)
            return k;
    
      // should not happen
      return 0;
   }

   public static int getValueRank(char val)
   {
      int k;
    
      for (k = 0; k < numValsInOrderingArray; k++)
         if (valueRanks[k] == val)
            return k;
    
      // should not happen
      return 0;
   }

   public static void arraySort(Card[] array, int arraySize)
   {
      for (int k = 0; k < arraySize; k++)
         if (!floatLargestToTop(array, arraySize - 1 - k))
            return;
   }

   private static boolean floatLargestToTop(Card[] array, int top)
   {
      boolean changed = false;
      Card temp;
    
      for (int k = 0; k < top; k++)
         if (array[k].compareTo(array[k + 1]) > 0)
         {
            temp = array[k];
            array[k] = array[k + 1];
            array[k + 1] = temp;
            changed = true;
         }
      ;
      return changed;
   }
}

Sample output
--------------------------------------------------------------------------------
Create Cards
--------------------------------------------------------------------------------
Add Cards to the CardQueue
--------------------------------------------------------------------------------
Show the whole queue:
T of spades
J of clubs
Q of diamonds
K of hearts
A of spades

--------------------------------------------------------------------------------
Remove cards one by one, while printing the returned card. removing cards for te
n times:
T of spades
J of clubs
Q of diamonds
K of hearts
A of spades
[Catched an error exception]
[Catched an error exception]
[Catched an error exception]
[Catched an error exception]
[Catched an error exception]
--------------------------------------------------------------------------------
Program shutted down
--------------------------------------------------------------------------------

------------------------------------------------------------------------------

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote