Skip to Content
CoursesCSC122โปรแกรมหาพื้นที่ผิวและปริมาตรลูกบาศก์ทรงสี่เหลี่ยม

โปรแกรมหาพื้นที่ผิวและปริมาตรลูกบาศก์ทรงสี่เหลี่ยม

โจทย์

Write a class of cuboid having the following requirements:

3 Attributes:

  • double width
  • double height
  • double length

2 Constructors:

  • First constructor is a default constructor having no parameters. The default construct will assign a value of width, height, and length of 1.
  • The second constructor is a constructor that accepts 3 inputs which are width, height, and length. When an object is created from this constructor, attribute of width, height, and length is assigned according the inputs.

2 Methods:

  • getVolumn() This method calculate volume of cuboid and return volume of type double as an output.
  • getSurface()This method calculate surface area of cuboid and return surface of type double as an output.

Hint:

  1. Use double as datatype for number data.
  2. Volume formula: width * height * length
  3. Surface formula: 2(width * height) + 2(width * length) + 2(height * length)
  4. The driver class is provided in the answer box. Please do not modify the driver class, otherwise your output may be corrupted.
InputOutput
11.0
6.0
2
3.0 4.5 5.5
74.25
109.5

โค้ดเริ่มต้น

import java.util.Scanner; public class CuboidTester{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int opt = sc.nextInt(); if(opt==1){ Cuboid c = new Cuboid(); System.out.println(c.getVolumn()); System.out.println(c.getSurface()); } else{ double x = sc.nextDouble(); double y = sc.nextDouble(); double z = sc.nextDouble(); Cuboid c = new Cuboid(x,y,z); System.out.println(c.getVolumn()); System.out.println(c.getSurface()); } } } class Cuboid { //put your code here }

โค้ด

import java.util.Scanner; public class CuboidTester{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int opt = sc.nextInt(); if(opt==1){ Cuboid c = new Cuboid(); System.out.println(c.getVolumn()); System.out.println(c.getSurface()); } else{ double x = sc.nextDouble(); double y = sc.nextDouble(); double z = sc.nextDouble(); Cuboid c = new Cuboid(x,y,z); System.out.println(c.getVolumn()); System.out.println(c.getSurface()); } } } class Cuboid { double width; double height; double length; public Cuboid() { this.width = 1; this.height = 1; this.length = 1; } public Cuboid(double width, double height, double length) { this.width = width; this.height = height; this.length = length; } public double getVolumn() { return width * height * length; } public double getSurface() { return 2 * (width * length) + 2 * (width * height) + 2 * (length * height); } }

คำอธิบาย

ปรับปรุงล่าสุด