编程创建一个立方体类 Cube,在其中定义三个变量 length,width,height 分别表示一个立 方体的长、宽和高,再定义一个方法 setCube 对这三个变量进行初始化,然后定义求立方体 的体积和表面积的方法。 (1)编写一个测试类,在 main 方法中创建立方体对象,求给定尺寸的立方体的体积和表面 积,并输入结果。 (2)改用构造方法实现长、宽和高的初始化。 (3)测试类放在包名为 com.sy3.exe01.test 包中,其它类放在 com.sy3.exa01 包中。 (知识点:类的定义,对象的创建,构造方法的使用) (注意:如果需要从键盘输入长宽高的数据时,请从测试类的 main 方法中输入,程序的其 它地方只接受传递的参数
时间: 2024-04-01 14:36:05 浏览: 46
好的,下面是代码实现:
```
// Cube.java
package com.sy3.exa01;
public class Cube {
private double length;
private double width;
private double height;
public Cube() {}
public Cube(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
public void setCube(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
public double getVolume() {
return length * width * height;
}
public double getSurfaceArea() {
return 2 * (length * width + width * height + height * length);
}
}
// Test.java
package com.sy3.exe01.test;
import com.sy3.exa01.Cube;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入立方体的长:");
double length = input.nextDouble();
System.out.print("请输入立方体的宽:");
double width = input.nextDouble();
System.out.print("请输入立方体的高:");
double height = input.nextDouble();
Cube cube = new Cube(length, width, height);
System.out.printf("该立方体的体积为:%.2f\n", cube.getVolume());
System.out.printf("该立方体的表面积为:%.2f\n", cube.getSurfaceArea());
input.close();
}
}
```
注意:代码中的 `com.sy3.exa01` 和 `com.sy3.exe01.test` 是包名,需要根据实际情况修改。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)