题目:
1. 定义长方体类Cuboid,要求如下:(1)私有成员变量包括长length、宽width和高height;(2)构造方法包括一个公共的空构造方法,一个能够初始化所有成员变量的构造方法;(3)包括所有的setter和getter方法,其中setter方法要求对形参进行验证,例如长、宽和高都大于0;(4)功能方法包括计算表面积getArea()、计算体积getCubage()、判断是否正方体isCube()、输出该长方体的长宽高printCuboid()、绘制该长方体(给出提示信息即可)drawing()。
测试一要求如下:(1)利用空构造方法创建一个新的长方体对象cuboidA,然后利用setter方法设置长宽高分别为1.5、2.6和18.6,(2)调用printCuboid()方法输出cuboidA的基本信息,调用isCube()方法判断是否正方体;(3)调用方法drawing()模拟绘制该长方体。
测试二要求如下:(1)利用构造方法创建一个具有长宽高分别为2.5、6.8和8.0的长方体对象cuboidB,然后利用setLength()方法修改length为4.6;(2)调用getArea()方法计算表面积;(3)调用getCubage计算该长方体的体积。
package com.jus.object;
public class Cuboid {
private double length;
private double width;
private double height;
public Cuboid() {
} //空构造方法
public Cuboid(double length, double width, double height) { //初始化所有成员变量的构造方法
this.length = length;
this.width = width;
this.height = height;
}
public double getLength() {
return length;
}
public void setLength(double length) {
if (length > 0) {
this.length = length;
} else {
throw new RuntimeException("不符合要求,长度必须大于0");
// System.exit(0);
}
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
if (width > 0) {
this.width = width;
} else {
throw new RuntimeException("不符合要求,宽度必须大于0");
//System.exit(0);
}
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
if (height > 0) {
this.height = height;
}else {
throw new RuntimeException("不符合要求,高度必须大于0");
//System.exit(0);
}
}
public double getArea(){
return 2.0 * (length * width + length * height + width * height);
}
public double getCubage(){
return length * width * height;
}
public boolean isCube(){
return length == width && width == height;
}
public void printCuboid(){
System.out.println("长方体的长:" + length + "宽:"+width + "高:" + height);
}
public void drawing(){
System.out.println("正在绘制长方体,长:" + length + "宽:" + width + "高:" + height);
}
}
package com.jus.object;
public class Text {
public static void main(String[] args) {
Cuboid cuboidA = new Cuboid();
cuboidA.setLength(1.5);
cuboidA.setWidth(2.6);
cuboidA.setHeight(18.6);
cuboidA.printCuboid();
System.out.println("是否是正方体:" + cuboidA.isCube());
cuboidA.drawing();
System.out.println("********************************************");
Cuboid cuboidB = new Cuboid(2.5,6.8,8.0);
cuboidB.setLength(4.6);
String area = String.format("%.1f",cuboidB.getArea());
String cubage = String.format("%.2f",cuboidB.getCubage()); //四舍五入保留两位小数
System.out.println("表面积:" + area);
System.out.println("体积:" + cubage);
}
}
运行效果如图: