//******************************************************************* // // File: TestBox.java // Subject: CS-112 AS5 Solutions // Date: April 09, 2001 // Author: Gabriel Loh // Classes: TestBox // Box // //******************************************************************* //=================================================================== // CLASS TestBox creates a few different boxes, prints out // some of their attributes, modifies one, and prints out // some more attributes. //=================================================================== public class TestBox { /* This is the main provided from the as5 webpage */ public static void main(String args[]) { Box b1 = new Box(); Box b2 = new Box(2); Box b3 = new Box(2,3,4); System.out.println("There were " + b1.count() + " boxes created."); System.out.println("The box volumes are: " + b1.volume() + "," + b2.volume() + "," + b3.volume() + "."); b3.scale(3); System.out.println("The volume of box 3 is now: " + b3.volume() + "."); if (b2.cube()) System.out.println("Box 2 is a cube."); if (! b3.cube()) System.out.println("Box 3 is not a cube."); } } // end of class TestBox //=================================================================== // CLASS Box describes a "rectangular prism" shape by the three // sidelengths of the shape. Constructors are provided for a // unit cube, an arbitrarily sized cube, and a general "box". // All sidelengths have integer values. //=================================================================== class Box { protected int x,y,z; // these are the side lengths of the box protected static int numBoxesCreated = 0; // create a unit box if no args given to constructor public Box() { x = 1; y = 1; z = 1; numBoxesCreated++; } // create a cube, all sides having length s public Box(int s) { x = s; y = s; z = s; numBoxesCreated++; } // create a box with the side lengths as specified public Box(int new_x, int new_y, int new_z) { x = new_x; y = new_y; z = new_z; numBoxesCreated++; } // return the volume of the box public int volume() { return mult3(x,y,z); // volume is product of the three side lengths } // return the total number of boxes ever created public int count() { return numBoxesCreated; } // returns true if all side lengths are equal (i.e. x=y=z) public boolean cube() { return ((x==y) && (y==z)); // condition evaluates to a boolean } // multiplies each side by factor public void scale(int factor) { x *= factor; y *= factor; z *= factor; } // private helper method for multiplying three int's private int mult3(int a, int b, int c) { return a*b*c; } } // end of class Box |