定义一个描述长方体的类 Box ,类中有三个整型的成员变量: length 、 width 和 height ,分别表示长方体的长、宽和高。定义 setInfo ( int )方法设置这三个变量的值;定义 volumn ()方法求长方体的体积并返回整型结果;定义 area ()方法求长方体的表面积并返回整型结果;定义 toString ()方法把长方体的长、宽、高,以及长方体的体积和表面积转化为字符串并返回字符串。
编写 Java 应用程序,测试类 Box ,使用类中定义的各个方法,并将其结果输出。
基于new bing部分指引作答:
下面是 Java 中 Box 类的实现,并包含了一个测试程序:
public class Box {
private int length;
private int width;
private int height;
// 设置长方体的长、宽、高
public void setInfo(int l, int w, int h) {
length = l;
width = w;
height = h;
}
// 计算长方体的体积
public int volume() {
return length * width * height;
}
// 计算长方体的表面积
public int area() {
return 2 * (length * width + width * height + height * length);
}
// 将长方体的信息转化为字符串
public String toString() {
String str = "长: " + length + ", 宽: " + width + ", 高: " + height + ", 体积: " + volume() + ", 表面积: " + area();
return str;
}
}
public class TestBox {
public static void main(String[] args) {
Box box = new Box();
box.setInfo(10, 5, 3); // 设置长方体的长、宽、高
System.out.println(box.toString()); // 输出长方体的信息
}
}
解释一下代码逻辑:
setInfo()
方法用于设置长方体的长、宽、高。volume()
方法计算长方体的体积并返回整型结果。area()
方法计算长方体的表面积并返回整型结果。toString()
方法将长方体的信息转化为字符串并以字符串形式返回。setInfo()
方法设置其长、宽、高。然后使用 toString()
方法输出长方体的信息。需要注意的是,由于题目要求实现 toString() 方法,所以我们在该方法内部将长方体的各个信息格式化成了一个字符串,并返回该字符串。也可以通过直接输出信息来实现这个类的测试。
下面是一个描述长方体类Box的Java代码实现:
public class Box {
private int length;
private int width;
private int height;
public void setInfo(int length, int width, int height) {
this.length = length;
this.width = width;
this.height = height;
}
public int volumn() {
return length * width * height;
}
public int area() {
return 2 * (length * width + width * height + length * height);
}
public String toString() {
return "Box: length=" + length + ", width=" + width + ", height=" + height
+ ", volumn=" + volumn() + ", area=" + area();
}
}
接下来是一个测试类的Java代码实现:
public class Main {
public static void main(String[] args) {
Box box = new Box();
box.setInfo(3, 4, 5);
System.out.println(box.toString());
}
}
程序运行结果如下:
Box: length=3, width=4, height=5, volumn=60, area=94
测试类中首先创建了一个Box类的对象,通过调用类的setInfo方法设置长方体的长、宽和高,然后分别调用volumn和area方法求解长方体的体积和表面积,最后调用toString方法将长方体的信息转化为字符串并输出。