Question

In the second part well begin with a recursive data structure that represents a tower of blocks. We represent such a Tower by its top block which for convenience well just take to be a char representing its colour, i.e something like B, G R or Y together with another Tower representing the rest of the blocks. The basic constructors and some utility functions are supplied. Your job will be to work out how to compute the height of a tower and the number of blocks in a tower of a given colour.

/**
* A recursive representation of a tower of blocks.
*
*
*/
public class Tower{

    /** The top block. */
    private char top;
  
    /** The rest of the tower. */
    private Tower rest;

    /**
     * Creates a new empty Tower.
     */
    public Tower() {
        this.top = ' ';
        this.rest = null;
    }
  
    /**
     * External classes can only create empty towers and manipulate
     * them using public methods, because this constructor is
     * private.
     * @param top the top block in this tower
     * @param rest the rest of the tower
     */
    private Tower(char top, Tower rest) {
        this.top = top;
        this.rest = rest;
    }

    /**
     * Returns true if this tower is empty, otherwise false. Empty
     * towers are represented with the top block being a space
     * character.
     * @return whether the tower is empty or not.
     */
    public boolean isEmpty() {
        return top == ' ';
    }
      
    /**
     * Creates a new tower by adding the given block to the top of
     * this tower.
     * @param block a block to add to the top of this tower.
     * @return a new tower created by adding a block to the top of
     * this tower.
     */
    public Tower add(char block) {
        return new Tower(block, this);
    }

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

/**
* A recursive representation of a tower of blocks.
*/
public class Tower {

   /** The top block. */
   private char top;

   /** The rest of the tower. */
   private Tower rest;

   /**
   * Creates a new empty Tower.
   */
   public Tower() {
       this.top = ' ';
       this.rest = null;
   }

   /**
   * External classes can only create empty towers and manipulate them using
   * public methods, because this constructor is private.
   *
   * @param top
   *            the top block in this tower
   * @param rest
   *            the rest of the tower
   */
   private Tower(char top, Tower rest) {
       this.top = top;
       this.rest = rest;
   }

   /**
   * Returns true if this tower is empty, otherwise false. Empty towers are
   * represented with the top block being a space character.
   *
   * @return whether the tower is empty or not.
   */
   public boolean isEmpty() {
       return top == ' ';
   }

   /**
   * Creates a new tower by adding the given block to the top of this tower.
   *
   * @param block
   *            a block to add to the top of this tower.
   * @return a new tower created by adding a block to the top of this tower.
   */
   public Tower add(char block) {
       return new Tower(block, this);
   }
  
   /**
   * Calculates the height of the tower recursively
   */
   private int height(Tower tower) {
       if (tower.rest == null)
           return 0;
       else {
           int height = 1;
           return (height + height(tower.rest));
       }
   }

   /**
   * Returns the height of the tower i.e. the number of blocks in the tower
   */
   public int height() {
       return height(this);
   }
  
   /**
   * Counts the number of 'c' blocks in the tower recursively
   */
   private int count(char c, Tower tower) {
       if (tower.rest == null)
           return 0;
       else {
           int count = (tower.top == c) ? 1 : 0;
           return (count + count(c, tower.rest));
       }
   }

   /**
   * Returns the number of blocks of 'c' (case sensitive) in the tower
   */
   public int count(char c) {
       return count(c, this);
   }

   @Override
   public String toString() {
       StringBuffer sb = new StringBuffer();

       if (!isEmpty()) {
           sb.append("\n" + top);
           Tower currBlock = rest;

           while (currBlock.rest != null) {
               sb.append("\n" + currBlock.top);
               currBlock = currBlock.rest;
           }
       } else
           sb.append("Tower is empty");

       return sb.toString();
   }
}

public class TowerTest {

   public static void main(String[] args) {

       // Create a new Tower
       Tower tower = new Tower();

       // Test if tower is empty
       System.out.println("Is Tower empty: " + tower.isEmpty());

       // Display the height of the tower
       System.out.println("Height of the tower: " + tower.height());

       // Display tower
       System.out.println("Tower: " + tower);

       // Add a block to the tower
       tower = tower.add('B');
       tower = tower.add('G');
       tower = tower.add('R');
       tower = tower.add('Y');

       System.out.println("\nAdding \'B\', \'G\', \'R\' and \'Y\' blocks to the tower");

       // Test if tower is empty
       System.out.println("Is Tower empty: " + tower.isEmpty());

       // Display the height of the tower
       System.out.println("Height of the tower: " + tower.height());

       // Display tower
       System.out.println("Tower: " + tower);

       // Display # of blocks of B
       System.out.println("Number of blocks of \'B\': " + tower.count('B'));

       // Display # of blocks of P
       System.out.println("Number of blocks of \'P\': " + tower.count('P'));
   }
}


SAMPLE OUTPUT:

Is Tower empty: true Height of the tower: 0 Tower: Tower is empty Adding B, G, R and Y blocks to the tower Is Tower e

Add a comment
Know the answer?
Add Answer to:
/** * A recursive representation of a tower of blocks. * * */ public class Tower{...
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
  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

  • Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element...

    Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element stored at this node */ private int element; // reference to the element stored at this node /** A reference to the subsequent node in the list */ private Node next; // reference to the subsequent node in the list /** * Creates a node with the given element and next node. * * @param e the element to be stored * @param n...

  • In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> {...

    In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> { /** Adds one element to the top of this stack. * @param element element to be pushed onto stack */ public void push (T element);    /** Removes and returns the top element from this stack. * @return T element removed from the top of the stack */ public T pop(); /** Returns without removing the top element of this stack. * @return T...

  • In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {...

    In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {    private BinaryTreeNode root;    /**    * Creates an empty binary tree.    */    public LinkedBinaryTree() {        root = null;    }    /**    * Creates a binary tree from an existing root.    */    public LinkedBinaryTree(BinaryTreeNode root) {        this.root = root;    }    /**    * Creates a binary tree with the specified element...

  • Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of...

    Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of the peek, isEmpty, size, and toString methods. See Base_A06Q1.java for a starting place and a description of these methods. Here is the base given: /** * Write a description of the program here. * * @author Lewis et al., (your name) * @version (program version) */ import java.util.Iterator; public class Base_A06Q1 { /** * Program entry point for stack testing. * @param args Argument...

  • In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These...

    In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These files will need to be added to your Java project. They provide data structure functionality that you will build over. It is suggested that you test if these files have been properly added to your project by confirming that Base_A05Q1.java compiles correctly. Complete the implementation of the ArrayStack class. Specifically, complete the implementations of the isEmpty, size, and toString methods. See Base_A05Q1.java for a...

  • Given code: /** * Provides some methods to manipulate text * */ public class LoopyText {...

    Given code: /** * Provides some methods to manipulate text * */ public class LoopyText { private String text;    /** * Creates a LoopyText object with the given text * @param theText the text for this LoopyText */ public LoopyText(String theText) { text = theText; }    //Your methods here } Given tester code: /** * Tests the methods of LoopyText. * @author Kathleen O'Brien */ public class LoopyTextTester { public static void main(String[] args) { LoopyText loopy =...

  • There is a data structure called a drop-out stack that behaves like a stack in every...

    There is a data structure called a drop-out stack that behaves like a stack in every respect except that if the stack size is n, then when the n+1element is pushed, the bottom element is lost. Implement a drop-out stack using links, by modifying the LinkedStack code. (size, n, is provided by the constructor. Request: Please create a separate driver class, in a different file, that tests on different types of entries and show result of the tests done on...

  • how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 }...

    how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 } class Stack { Node head; int size; Stack() //default constructor { this.head=null; this.size=0; } //Input = data //Output = void (just adds value to list) // method pushes elements on stack // time: O(1) // space: O(1) public void push(int data) { Node node=new Node(data); node.next=head; head=node; size++; } //Input = none //Output = top of stack // method pops value from top of...

  • Step 3 Develop the following class: Class Name: ImprovedQueue<T> Access Modifier: public Implements: QueueInterface<T> Instance variables...

    Step 3 Develop the following class: Class Name: ImprovedQueue<T> Access Modifier: public Implements: QueueInterface<T> Instance variables Name: front Access modifier: private Data type: QueueNode<T> Constructors: Name: ImprovedQueue Access modifier: public Parameters: none (default constructor) Task: sets the value of front to null Methods Name: isEmpty Access modifier: public Parameters: none Return type: boolean Task: returns true if the front is equal to null; otherwise return false Name: dequeue                           Access modifier: public Parameters: none Return type: T (parameterized type) Task: makes...

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
ADVERTISEMENT