设计并实现Box类,它包含盒子的高度、宽带和深度的实例数据:还包含布尔变量full这个实例数据,变量full表示盒子是否满了。所有数据都定义为私有。定义Box构造函数接收并初始化盒子的高度、宽带和深度。每次新创建的Box都为空,构造函数将full初始化为假。该类所有实例都有getter和setter方法;该类还包含了一个计算盒子体积的方法。 该类包含一个toString方法,用来返回一行关于盒子的描述。 例如,输入的长、宽、高分别为4,如果盒子为空,则输出: Box is empty, The Volumn is 64 若将盒子的宽度修改为5,盒子设置为满,则输出: Box is full, The Volumn is 80 创建一个测试类BoxTest,其main方法输入盒子的长、宽、高,实例化一个Box对象,并输出盒子的描述。 根据以下的测试类,在空格出填入Box类的设计程序。
时间: 2024-02-05 16:14:11 浏览: 201
```
public class Box {
private double height;
private double width;
private double depth;
private boolean full;
public Box(double height, double width, double depth) {
this.height = height;
this.width = width;
this.depth = depth;
this.full = false;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getDepth() {
return depth;
}
public void setDepth(double depth) {
this.depth = depth;
}
public boolean isFull() {
return full;
}
public void setFull(boolean full) {
this.full = full;
}
public double calculateVolume() {
return height * width * depth;
}
public String toString() {
String status = full ? "full" : "empty";
return "Box is " + status + ", The Volume is " + calculateVolume();
}
}
```
测试类BoxTest的代码:
```
import java.util.Scanner;
public class BoxTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the height of the box: ");
double height = scanner.nextDouble();
System.out.print("Enter the width of the box: ");
double width = scanner.nextDouble();
System.out.print("Enter the depth of the box: ");
double depth = scanner.nextDouble();
Box box = new Box(height, width, depth);
System.out.println(box);
System.out.print("Set the width of the box to: ");
double newWidth = scanner.nextDouble();
box.setWidth(newWidth);
System.out.print("Is the box full? (true/false): ");
boolean isFull = scanner.nextBoolean();
box.setFull(isFull);
System.out.println(box);
scanner.close();
}
}
```
阅读全文