import java.util.*; class TriangleAreaComparator implements Comparator<Triangle> { @Override public int compare(Triangle o1,Triangle o2) { if(o1.getArea() == o2.getArea()){ return 0; } else{ return o1.getArea() > o2.getArea() ? 1 : -1; } } } public class Triangle implements Comparable<Triangle> { private double a, b, c, area; void scanA(double a){ this.a = a; } void scanB(double b){ this.b = b; } void scanC(double c){ this.c = c; } double getA(){ return a; } double getB(){ return b; } double getC(){ return c; } double getArea(){ return area; } @Override public int compareTo(Triangle o) { if(this.area == o.area){ return 0; } else{ return this.area > o.area ? 1 : -1; } } void computeArea(double a, double b, double c){ double p = (a + b + c) / 2; //海伦公式 area = Math.sqrt(p * (p - a) * (p - b) * (p - c)); System.out.printf("该三角形面积为:%.2f\n" ,area); } }根据这段代码写出主函数调用代码
时间: 2024-02-14 19:12:54 浏览: 136
好的,下面是一个简单的主函数调用代码示例,它使用上面提供的Triangle和TriangleAreaComparator类:
```java
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Triangle[] triangles = new Triangle[3];
// 输入三角形的三边长,并计算面积
for (int i = 0; i < 3; i++) {
System.out.println("请输入第" + (i+1) + "个三角形的三边长:");
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
Triangle triangle = new Triangle();
triangle.scanA(a);
triangle.scanB(b);
triangle.scanC(c);
triangle.computeArea(a, b, c);
triangles[i] = triangle;
}
// 按面积大小排序并输出
Arrays.sort(triangles, new TriangleAreaComparator());
System.out.println("按面积从小到大排序:");
for (Triangle triangle : triangles) {
System.out.printf("三边长为(%.2f, %.2f, %.2f)的三角形面积为:%.2f\n",
triangle.getA(), triangle.getB(), triangle.getC(), triangle.getArea());
}
}
}
```
这个程序会要求用户输入三个三角形的三边长,并计算它们的面积。然后,它会使用TriangleAreaComparator类来按面积从小到大对三角形进行排序,并输出每个三角形的三边长和面积。
希望这个示例代码可以帮助你!
阅读全文