โปรแกรมหาพื้นที่ผิวและปริมาตรลูกบาศก์ทรงสี่เหลี่ยม
โจทย์
Write a class of cuboid having the following requirements:
3 Attributes:
double widthdouble heightdouble length
2 Constructors:
- First constructor is a default constructor having no parameters. The default construct will assign a value of
width,height, andlengthof 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, andlengthis 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:
- Use double as datatype for number data.
- Volume formula: width * height * length
- Surface formula: 2(width * height) + 2(width * length) + 2(height * length)
- The driver class is provided in the answer box. Please do not modify the driver class, otherwise your output may be corrupted.
| Input | Output |
|---|---|
| 1 | 1.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);
}
}คำอธิบาย
ปรับปรุงล่าสุด