Pro - 4

Pro 4 - Write a program to find the volume of a box having its side w, h, d means width, height and depth. Its volume is v=w*h*d and also find the surface area given by the formula s=2(wh+hd+dw), use appropriate constructors for the above.


class Box {
  double width;
  double height;
  double depth;

  // This is the constructor for Box.
  Box(double w, double h, double d) {
    width = w;
    height = h;
    depth = d;
  }

  // compute and return volume - Volume of box
  double volume() {
    return width * height * depth;
  }
  // compute and return volume - surfface area
  double surface() {
    return (2*((width * height) + (height * depth) + (depth * width))); 

  }

}

This is a  Main Class to run the Above Java Class

class BoxDemo {
  public static void main(String args[]) {
    // declare, allocate, and initialize Box objects
    Box mybox1 = new Box(10, 20, 15);
    Box mybox2 = new Box(3, 6, 9);

    double vol, sur;

    // get volume of first box
    vol = mybox1.volume();
   vol = mybox1.surface();
    System.out.println("Volume is " + vol);
    System.out.println("surface is " + sur);
// get volume of second box vol = mybox2.volume(); vol = mybox2.surface();
    System.out.println("Volume is " + vol);
    System.out.println("surface is " + sur);
  }
}


Output of Above Java Program
Volume is 3000.0
Volume is 162.0

No comments:

Post a Comment