See below.
Here is Forest
along with a testing class.
// Forest.java // public class Forest { // instance variables private Tree tree0=null, tree1=null, tree2=null, tree3=null; // methods public void setTree( int treeNum, Tree tree ) { if ( treeNum == 0 ) tree0 = tree; else if ( treeNum == 1 ) tree1 = tree; else if ( treeNum == 2 ) tree2 = tree; else if ( treeNum == 3 ) tree3 = tree; } public Tree getTree( int treeNum ) { if ( treeNum == 0 ) return tree0; else if ( treeNum == 1 ) return tree1; else if ( treeNum == 2 ) return tree2; else if ( treeNum == 3 ) return tree3; else return null; } // build a string public String toString() { if ( tree0==null && tree1==null && tree2==null && tree3==null ) return "No Trees in Forest"; String str = "Forest:\n"; if ( tree0 != null ) str += "Tree 0: " + tree0.toString() + "\n"; if ( tree1 != null ) str += "Tree 1: " + tree1.toString() + "\n"; if ( tree2 != null ) str += "Tree 2: " + tree2.toString() + "\n"; if ( tree3 != null ) str += "Tree 3: " + tree3.toString() + "\n"; return str; } }
To compile you will need ForestTester.java, Forest.java, Tree.java, Cone.java, and Cylinder.java all in the same directory.
public class ForestTester { public static void main( String[] args ) { Forest myForest = new Forest(); double trunkR = 1.0, trunkH = 1.0, branchR = 8.0, branchH = 10.0 ; Tree tree = new Tree( trunkH, trunkR, branchH, branchR, 1, 2, 3 ); myForest.setTree( 0, tree ); trunkR = 1.4; trunkH = 2.0; branchR = 15.0; branchH = 30.0 ; tree = new Tree( trunkH, trunkR, branchH, branchR, 5, 8, 0 ); myForest.setTree( 2, tree ); System.out.println( myForest ); } }
The output should be:
Forest: Tree 0: Height: 11.0, width: 8.0, area: 529.2012441663949, volume: 673.3480254194124 Tree 2: Height: 32.0, width: 15.0, area: 2296.2381209719183, volume: 7080.898513779107
Does toString()
need to be explicitly included in the statement
if ( tree0 != null ) str += "Tree 0: " + tree0.toString() + "\n";