go to previous page   go to home page   go to next page

Answer:

See below.


Grow Method

// Tree.java
//
public class Tree
{
  // instance variables
  private double x, y, z;
  private Cone branches;
  private Cylinder trunk;  
  
  // constructor
  public Tree( double trRad, double trHeight, double brRad, double brHeight, double x, double y, double z)
  {
    trunk = new Cylinder( trHeight, trRad );
    branches = new Cone( brHeight, brRad );
    this.x = x; this.y = y; this.z = z;
  }
  
  // methods
  public String toString()
  {
    double totalHeight = branches.getHeight() + trunk.getHeight();
    double width = branches.getRadius();
    return "Tree. Height: "  + totalHeight + ", width: " + width + 
           ", area: " + area() + ", volume: " + volume() ;
  }
  
  // more methods
  public double volume()
  {
   // return the sum of two volumes
   return trunk.volume() + branches.volume();
  }

  public double area()
  {
   // return the sum of two areas
   // minus twice the area of the trunk's circular top
   double total = trunk.area() + branches.area();
   double rad = trunk.getRadius();
   double circle = Math.PI*rad*rad;
   return total - 2*circle;
  }

  public void grow( double rate )
  {
   // increase all dimensions by rate
   double bHeight = branches.getHeight();
   branches.setHeight( bHeight*(1.0+rate) );
   
   double bRadius = branches.getRadius();
   branches.setRadius( bRadius*(1.0+rate) );

   double tHeight = trunk.getHeight();
   trunk.setHeight( tHeight*(1.0+rate) );
   
   double tRadius = trunk.getRadius();
   trunk.setRadius( tRadius*(1.0+rate) );
  }
    
} 

It might be good to test things:

public class TreeTester
{
  public static void main( String[] args )
  {
    double trunkR = 1.0, trunkH = 1.0, branchR = 11.0, branchH = 10.0 ;
    
    Tree myTree = new Tree( trunkR, trunkH, branchR, branchH, 1, 2, 3  );
    System.out.println("myTree: " + myTree + "\n");
    
    myTree.grow( 0.10 );
    System.out.println("bigger Tree: " + myTree);
  }
}


QUESTION 11:

Should Tree objects have setter and getter methods?


go to previous page   go to home page   go to next page