编写一个java程序将求和、求平均值、排序等类放入“算术包”中,将计算三角形面积,计算矩形面积等类放入“几何包”,并在”应用包“中的测试类中计算几个图形的面积平均值等。
时间: 2024-10-23 21:16:38 浏览: 20
输入两个正整数m和n求其最大公约数和最小公倍数 (2).pdf
在Java中,为了组织代码并增强模块化,我们可以创建包(packages)来分别存放相关的类。首先,我们需要创建三个包:`算术包`、`几何包`和`应用包`。
1. **算术包** (ArithmeticPackage):
- 定义一个`SumCalculator.java` 类用于求和操作,如整数或浮点数数组的总和。
```java
package 算术包;
public class SumCalculator {
public static double sum(double[] numbers) {
double total = 0;
for (double number : numbers) {
total += number;
}
return total;
}
}
```
- 同样地,可以有`AverageCalculator.java` 类计算平均值。
2. **几何包** (GeometryPackage):
- 创建`TriangleAreaCalculator.java` 和 `RectangleAreaCalculator.java` 分别计算三角形和矩形的面积。
```java
package 几何包;
public class TriangleAreaCalculator {
public static double area(double base, double height) {
return 0.5 * base * height;
}
}
public class RectangleAreaCalculator {
public static double area(double length, double width) {
return length * width;
}
}
```
3. **应用包** (ApplicationPackage):
- 在这里,我们编写`TestGeometry.java` 或者类似名称的测试类。
```java
package 应用包;
import 算术包.SumCalculator;
import 几何包.TriangleAreaCalculator;
import 几何包.RectangleAreaCalculator;
public class TestGeometry {
public static void main(String[] args) {
double[] numbers = {1, 2, 3, 4, 5};
System.out.println("Numbers sum: " + SumCalculator.sum(numbers));
double triangleBase = 5, triangleHeight = 3;
double triangleArea = TriangleAreaCalculator.area(triangleBase, triangleHeight);
System.out.println("Triangle area: " + triangleArea);
double rectangleLength = 10, rectangleWidth = 6;
double rectangleArea = RectangleAreaCalculator.area(rectangleLength, rectangleWidth);
System.out.println("Rectangle area: " + rectangleArea);
// 计算平均面积
double[] areas = {triangleArea, rectangleArea};
double averageArea = SumCalculator.sum(areas) / areas.length;
System.out.println("Average area: " + averageArea);
}
}
```
阅读全文